Skip to content

Commit

Permalink
Added blacklist and optimized connection scheduling logic.
Browse files Browse the repository at this point in the history
  • Loading branch information
AstaFrode committed Aug 23, 2022
1 parent e8bcb41 commit ebe2128
Show file tree
Hide file tree
Showing 8 changed files with 281 additions and 75 deletions.
39 changes: 29 additions & 10 deletions cmd/cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -460,7 +460,7 @@ func Command_Run_Runfunc(cmd *cobra.Command, args []string) {
}

// start-up
task.Run()
go task.Run()
rpc.Rpc_Main()
}

Expand Down Expand Up @@ -629,9 +629,19 @@ func Command_UpdateAddress_Runfunc(cmd *cobra.Command, args []string) {
//Parse command arguments and configuration file
parseFlags(cmd)

txhash, _, err := chain.UpdateAddress(configs.C.SignatureAcc, base58.Encode([]byte(os.Args[2])))
if txhash == "" {
log.Printf("\x1b[%dm[err]\x1b[0m Update failed, Please try again later.%v\n", 41, err)
txhash, err := chain.UpdateAddress(configs.C.SignatureAcc, base58.Encode([]byte(os.Args[2])))
if err != nil {
if err.Error() == chain.ERR_Empty {
log.Println("[err] Please check your wallet balance.")
} else {
if txhash != "" {
msg := configs.HELP_common + fmt.Sprintf(" %v\n", txhash)
msg += configs.HELP_UpdateAddress
log.Printf("[pending] %v\n", msg)
} else {
log.Printf("[err] %v.\n", err)
}
}
os.Exit(1)
}
log.Printf("\x1b[%dm[ok]\x1b[0m success\n", 42)
Expand All @@ -651,9 +661,19 @@ func Command_UpdateIncome_Runfunc(cmd *cobra.Command, args []string) {
}
//Parse command arguments and configuration file
parseFlags(cmd)
txhash, _, err := chain.UpdateIncome(configs.C.SignatureAcc, types.NewAccountID(pubkey))
if txhash == "" {
log.Printf("\x1b[%dm[err]\x1b[0m Update failed, Please try again later.%v\n", 41, err)
txhash, err := chain.UpdateIncome(configs.C.SignatureAcc, types.NewAccountID(pubkey))
if err != nil {
if err.Error() == chain.ERR_Empty {
log.Println("[err] Please check your wallet balance.")
} else {
if txhash != "" {
msg := configs.HELP_common + fmt.Sprintf(" %v\n", txhash)
msg += configs.HELP_UpdataBeneficiary
log.Printf("[pending] %v\n", msg)
} else {
log.Printf("[err] %v.\n", err)
}
}
os.Exit(1)
}
log.Printf("\x1b[%dm[ok]\x1b[0m success\n", 42)
Expand Down Expand Up @@ -773,9 +793,8 @@ func parseProfile() {
configs.Shared_g = data.Shared_g
configs.Shared_params = data.Shared_params
configs.Spk = data.Spk
pattern.SetMinerAcc(acc)
pattern.SetMinerSignAddr(configs.C.IncomeAcc)
}

pattern.SetMinerAcc(acc)
pattern.SetMinerSignAddr(configs.C.IncomeAcc)
configs.BaseDir = filepath.Join(configs.C.MountedPath, addr, configs.BaseDir)
}
6 changes: 6 additions & 0 deletions configs/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,12 @@ const (
HELP_register = ` 3.Check the Sminer_Registered transaction event result in the block hash above:
If system.ExtrinsicFailed is prompted, it means failure;
If system.ExtrinsicSuccess is prompted, it means success;`
HELP_UpdateAddress = ` 3.Check the Sminer_UpdataIp transaction event result in the block hash above:
If system.ExtrinsicFailed is prompted, it means failure;
If system.ExtrinsicSuccess is prompted, it means success;`
HELP_UpdataBeneficiary = ` 3.Check the Sminer_UpdataBeneficiary transaction event result in the block hash above:
If system.ExtrinsicFailed is prompted, it means failure;
If system.ExtrinsicSuccess is prompted, it means success;`
)

// Miner info
Expand Down
40 changes: 40 additions & 0 deletions internal/chain/chainstate.go
Original file line number Diff line number Diff line change
Expand Up @@ -234,3 +234,43 @@ func GetBlockHeight(api *gsrpc.SubstrateAPI) (types.U32, error) {
}
return types.U32(block.Block.Header.Number), nil
}

func GetAccountInfo(puk []byte) (types.AccountInfo, error) {
defer func() {
if err := recover(); err != nil {
Pnc.Sugar().Errorf("%v", tools.RecoverError(err))
}
}()

var data types.AccountInfo

api, err := GetRpcClient_Safe(configs.C.RpcAddr)
defer Free()
if err != nil {
return data, errors.Wrap(err, "[GetRpcClient_Safe]")
}

meta, err := GetMetadata(api)
if err != nil {
return data, errors.Wrap(err, "[GetMetadata]")
}

b, err := types.EncodeToBytes(types.NewAccountID(puk))
if err != nil {
return data, errors.Wrap(err, "[EncodeToBytes]")
}

key, err := types.CreateStorageKey(meta, "System", "Account", b)
if err != nil {
return data, errors.Wrap(err, "[CreateStorageKey]")
}

ok, err := api.RPC.State.GetStorageLatest(key, &data)
if err != nil {
return data, errors.Wrap(err, "[GetStorageLatest]")
}
if !ok {
return data, errors.New(ERR_Empty)
}
return data, nil
}
98 changes: 66 additions & 32 deletions internal/chain/transaction.go
Original file line number Diff line number Diff line change
Expand Up @@ -763,7 +763,7 @@ func ClearFiller(api *gsrpc.SubstrateAPI, signaturePrk string) (int, error) {
}
}

func UpdateAddress(transactionPrK, addr string) (string, int, error) {
func UpdateAddress(transactionPrK, addr string) (string, error) {
var (
err error
accountInfo types.AccountInfo
Expand All @@ -777,50 +777,50 @@ func UpdateAddress(transactionPrK, addr string) (string, int, error) {

api, err := NewRpcClient(configs.C.RpcAddr)
if err != nil {
return "", configs.Code_500, errors.Wrap(err, "NewRpcClient err")
return "", errors.Wrap(err, "NewRpcClient err")
}

keyring, err := signature.KeyringPairFromSecret(transactionPrK, 0)
if err != nil {
return "", configs.Code_500, errors.Wrap(err, "KeyringPairFromSecret err")
return "", errors.Wrap(err, "KeyringPairFromSecret err")
}

meta, err := api.RPC.State.GetMetadataLatest()
if err != nil {
return "", configs.Code_500, errors.Wrap(err, "GetMetadataLatest err")
return "", errors.Wrap(err, "GetMetadataLatest err")
}

c, err := types.NewCall(meta, ChainTx_Sminer_UpdateIp, types.Bytes([]byte(addr)))
if err != nil {
return "", configs.Code_500, errors.Wrap(err, "NewCall err")
return "", errors.Wrap(err, "NewCall err")
}

ext := types.NewExtrinsic(c)
if err != nil {
return "", configs.Code_500, errors.Wrap(err, "NewExtrinsic err")
return "", errors.Wrap(err, "NewExtrinsic err")
}

genesisHash, err := api.RPC.Chain.GetBlockHash(0)
if err != nil {
return "", configs.Code_500, errors.Wrap(err, "GetBlockHash err")
return "", errors.Wrap(err, "GetBlockHash err")
}

rv, err := api.RPC.State.GetRuntimeVersionLatest()
if err != nil {
return "", configs.Code_500, errors.Wrap(err, "GetRuntimeVersionLatest err")
return "", errors.Wrap(err, "GetRuntimeVersionLatest err")
}

key, err := types.CreateStorageKey(meta, "System", "Account", keyring.PublicKey)
if err != nil {
return "", configs.Code_500, errors.Wrap(err, "CreateStorageKey System Account err")
return "", errors.Wrap(err, "CreateStorageKey System Account err")
}

ok, err := api.RPC.State.GetStorageLatest(key, &accountInfo)
if err != nil {
return "", configs.Code_500, errors.Wrap(err, "GetStorageLatest err")
return "", errors.Wrap(err, "GetStorageLatest err")
}
if !ok {
return "", configs.Code_500, errors.New("GetStorageLatest return value is empty")
return "", errors.New("GetStorageLatest return value is empty")
}

o := types.SignatureOptions{
Expand All @@ -836,32 +836,49 @@ func UpdateAddress(transactionPrK, addr string) (string, int, error) {
// Sign the transaction
err = ext.Sign(keyring, o)
if err != nil {
return "", configs.Code_500, errors.Wrap(err, "Sign err")
return "", errors.Wrap(err, "Sign err")
}

// Do the transfer and track the actual status
sub, err := api.RPC.Author.SubmitAndWatchExtrinsic(ext)
if err != nil {
return "", configs.Code_500, errors.Wrap(err, "SubmitAndWatchExtrinsic err")
return "", errors.Wrap(err, "SubmitAndWatchExtrinsic err")
}
defer sub.Unsubscribe()
timeout := time.After(time.Second * configs.TimeToWaitEvents_S)
for {
select {
case status := <-sub.Chan():
if status.IsInBlock {
events := MyEventRecords{}
txhash, _ := types.EncodeToHexString(status.AsInBlock)
return txhash, configs.Code_600, nil
keye, err := types.CreateStorageKey(meta, "System", "Events", nil)
if err != nil {
return txhash, errors.Wrap(err, "GetKeyEvents")
}
h, err := api.RPC.State.GetStorageRaw(keye, status.AsInBlock)
if err != nil {
return txhash, errors.Wrap(err, "GetStorageRaw")
}

types.EventRecordsRaw(*h).DecodeEventRecords(meta, &events)

if len(events.Sminer_UpdataIp) > 0 {
if string(events.Sminer_UpdataIp[0].Acc[:]) == string(pattern.GetMinerAcc()) {
return txhash, nil
}
}
return txhash, errors.New(ERR_Failed)
}
case err = <-sub.Err():
return "", configs.Code_500, err
return "", errors.Wrap(err, "<-sub")
case <-timeout:
return "", configs.Code_500, errors.Errorf("timeout")
return "", errors.Errorf("timeout")
}
}
}

func UpdateIncome(transactionPrK string, acc types.AccountID) (string, int, error) {
func UpdateIncome(transactionPrK string, acc types.AccountID) (string, error) {
var (
err error
accountInfo types.AccountInfo
Expand All @@ -873,49 +890,49 @@ func UpdateIncome(transactionPrK string, acc types.AccountID) (string, int, erro
}()
api, err := NewRpcClient(configs.C.RpcAddr)
if err != nil {
return "", configs.Code_500, errors.Wrap(err, "NewRpcClient err")
return "", errors.Wrap(err, "NewRpcClient err")
}
keyring, err := signature.KeyringPairFromSecret(transactionPrK, 0)
if err != nil {
return "", configs.Code_500, errors.Wrap(err, "KeyringPairFromSecret err")
return "", errors.Wrap(err, "KeyringPairFromSecret err")
}

meta, err := api.RPC.State.GetMetadataLatest()
if err != nil {
return "", configs.Code_500, errors.Wrap(err, "GetMetadataLatest err")
return "", errors.Wrap(err, "GetMetadataLatest err")
}

c, err := types.NewCall(meta, ChainTx_Sminer_UpdateBeneficiary, acc)
if err != nil {
return "", configs.Code_500, errors.Wrap(err, "NewCall err")
return "", errors.Wrap(err, "NewCall err")
}

ext := types.NewExtrinsic(c)
if err != nil {
return "", configs.Code_500, errors.Wrap(err, "NewExtrinsic err")
return "", errors.Wrap(err, "NewExtrinsic err")
}

genesisHash, err := api.RPC.Chain.GetBlockHash(0)
if err != nil {
return "", configs.Code_500, errors.Wrap(err, "GetBlockHash err")
return "", errors.Wrap(err, "GetBlockHash err")
}

rv, err := api.RPC.State.GetRuntimeVersionLatest()
if err != nil {
return "", configs.Code_500, errors.Wrap(err, "GetRuntimeVersionLatest err")
return "", errors.Wrap(err, "GetRuntimeVersionLatest err")
}

key, err := types.CreateStorageKey(meta, "System", "Account", keyring.PublicKey)
if err != nil {
return "", configs.Code_500, errors.Wrap(err, "CreateStorageKey System Account err")
return "", errors.Wrap(err, "CreateStorageKey System Account err")
}

ok, err := api.RPC.State.GetStorageLatest(key, &accountInfo)
if err != nil {
return "", configs.Code_500, errors.Wrap(err, "GetStorageLatest err")
return "", errors.Wrap(err, "GetStorageLatest err")
}
if !ok {
return "", configs.Code_500, errors.New("GetStorageLatest return value is empty")
return "", errors.New("GetStorageLatest return value is empty")
}

o := types.SignatureOptions{
Expand All @@ -931,27 +948,44 @@ func UpdateIncome(transactionPrK string, acc types.AccountID) (string, int, erro
// Sign the transaction
err = ext.Sign(keyring, o)
if err != nil {
return "", configs.Code_500, errors.Wrap(err, "Sign err")
return "", errors.Wrap(err, "Sign err")
}

// Do the transfer and track the actual status
sub, err := api.RPC.Author.SubmitAndWatchExtrinsic(ext)
if err != nil {
return "", configs.Code_500, errors.Wrap(err, "SubmitAndWatchExtrinsic err")
return "", errors.Wrap(err, "SubmitAndWatchExtrinsic err")
}
defer sub.Unsubscribe()
timeout := time.After(time.Second * configs.TimeToWaitEvents_S)
for {
select {
case status := <-sub.Chan():
if status.IsInBlock {
events := MyEventRecords{}
txhash, _ := types.EncodeToHexString(status.AsInBlock)
return txhash, configs.Code_600, nil
keye, err := types.CreateStorageKey(meta, "System", "Events", nil)
if err != nil {
return txhash, errors.Wrap(err, "GetKeyEvents")
}
h, err := api.RPC.State.GetStorageRaw(keye, status.AsInBlock)
if err != nil {
return txhash, errors.Wrap(err, "GetStorageRaw")
}

types.EventRecordsRaw(*h).DecodeEventRecords(meta, &events)

if len(events.Sminer_UpdataBeneficiary) > 0 {
if string(events.Sminer_UpdataBeneficiary[0].Acc[:]) == string(pattern.GetMinerAcc()) {
return txhash, nil
}
}
return txhash, errors.New(ERR_Failed)
}
case err = <-sub.Err():
return "", configs.Code_500, err
return "", errors.Wrap(err, "<-sub")
case <-timeout:
return "", configs.Code_500, errors.Errorf("timeout")
return "", errors.Errorf("timeout")
}
}
}
Loading

0 comments on commit ebe2128

Please sign in to comment.