From 6de679f62726f320ee2c6db437eb7a3a1095f800 Mon Sep 17 00:00:00 2001 From: kch Date: Fri, 3 Nov 2023 04:10:22 +0000 Subject: [PATCH 1/6] replace base58, base64, gob to internal function --- chain/blockvalidator.go | 20 +++---- chain/chainanchor.go | 4 +- chain/chaindb.go | 30 ++++------- chain/chaindbForRaft.go | 21 +++----- chain/chainhandle.go | 12 ++--- chain/chainservice.go | 20 +++---- chain/chainverifier.go | 6 +-- chain/common.go | 2 +- chain/orphanpool.go | 2 +- chain/recover.go | 18 +++---- chain/reorg.go | 2 +- chain/signVerifier.go | 2 +- cmd/aergocli/cmd/blockchain_test.go | 6 +-- cmd/aergocli/cmd/committx_test.go | 6 +-- cmd/aergocli/cmd/contract.go | 6 +-- cmd/aergocli/cmd/enterprise.go | 4 +- cmd/aergocli/cmd/enterprise_test.go | 6 +-- cmd/aergocli/cmd/getblock.go | 4 +- cmd/aergocli/cmd/getstate.go | 4 +- cmd/aergocli/cmd/gettx.go | 4 +- cmd/aergocli/cmd/keygen.go | 4 +- cmd/aergocli/cmd/listblocks.go | 4 +- cmd/aergocli/cmd/receipt.go | 4 +- cmd/aergocli/cmd/sendtx.go | 4 +- cmd/aergocli/cmd/sendtx_test.go | 6 +-- cmd/aergocli/cmd/signtx.go | 4 +- cmd/aergocli/cmd/signtx_test.go | 4 +- cmd/aergocli/cmd/vote.go | 6 +-- cmd/aergocli/util/base58addr.go | 48 ++++++++--------- cmd/aergocli/util/base58addr_test.go | 12 ++--- cmd/aergocli/util/encoding/json/decode.go | 4 +- cmd/aergocli/util/encoding/json/encode.go | 4 +- cmd/aergoluac/encoding/codeEncoding.go | 6 +-- cmd/aergosvr/init.go | 4 +- cmd/colaris/cmd/current.go | 5 +- consensus/chain/block.go | 6 +-- consensus/impl/dpos/blockfactory.go | 4 +- consensus/impl/dpos/lib_test.go | 4 +- consensus/impl/raftv2/blockfactory.go | 2 +- consensus/impl/raftv2/cluster.go | 8 +-- consensus/impl/sbp/sbp.go | 2 +- consensus/raftCommon.go | 12 ++--- contract/enterprise/validate.go | 4 +- contract/statesql.go | 2 +- contract/system/execute.go | 4 +- contract/system/execute_test.go | 4 +- contract/system/vote.go | 7 ++- contract/system/vote_test.go | 8 +-- contract/system/voteresult.go | 13 +++-- contract/system/vprt.go | 6 +-- contract/system/vprt_test.go | 4 +- contract/vm.go | 6 +-- contract/vm_callback.go | 4 +- contract/vm_direct/vm_direct.go | 52 +++++++++---------- contract/vm_dummy/vm_dummy.go | 2 +- internal/enc/base58.go | 13 +++++ internal/enc/{bstr_test.go => base58_test.go} | 6 +-- internal/enc/base58check.go | 13 +++++ internal/enc/base64.go | 11 ++++ internal/enc/bstr.go | 13 ----- internal/merkle/merkle_test.go | 15 ++---- mempool/mempool.go | 12 ++--- mempool/txverifier.go | 2 +- p2p/actorwork.go | 4 +- p2p/const_test.go | 23 ++++---- p2p/hashreceiver_test.go | 2 +- p2p/msgorder.go | 2 +- p2p/p2pkey/nodekey.go | 2 +- p2p/p2putil/certificate_test.go | 6 +-- p2p/p2putil/protobuf_test.go | 2 +- p2p/p2putil/util.go | 4 +- p2p/p2putil/util_test.go | 4 +- p2p/subproto/block.go | 4 +- p2p/subproto/blockhash_test.go | 4 +- p2p/subproto/bp.go | 4 +- p2p/subproto/bp_test.go | 2 +- p2p/subproto/getblock.go | 4 +- p2p/subproto/getblock_test.go | 4 +- p2p/subproto/ping_test.go | 2 +- p2p/subproto/raftstub.go | 2 +- p2p/subproto/tx.go | 2 +- p2p/subproto/tx_test.go | 2 +- p2p/synctx_test.go | 6 +-- p2p/txreceiver.go | 2 +- p2p/v030/v030io_test.go | 4 +- p2p/v030/v032handshake.go | 2 +- p2p/v030/v033handshake.go | 2 +- p2p/v200/v200handshake.go | 2 +- rpc/grpcserver_test.go | 21 ++++---- state/chainstatedb.go | 8 +-- state/statedata.go | 16 ++---- state/statedb.go | 4 +- state/storage.go | 4 +- syncer/blockfetcher.go | 24 ++++----- syncer/blockprocessor.go | 16 +++--- syncer/finder.go | 6 +-- syncer/hashfetcher.go | 10 ++-- types/account.go | 10 ++-- types/blockchain.go | 6 +-- types/common.go | 12 ++--- types/genesis_test.go | 2 +- types/logging.go | 7 +-- types/logging_test.go | 5 +- types/p2p_test.go | 2 +- types/p2plogging.go | 24 ++++----- types/receipt.go | 8 +-- types/state.go | 2 +- types/transaction.go | 4 +- 108 files changed, 396 insertions(+), 429 deletions(-) create mode 100644 internal/enc/base58.go rename internal/enc/{bstr_test.go => base58_test.go} (88%) create mode 100644 internal/enc/base58check.go create mode 100644 internal/enc/base64.go delete mode 100644 internal/enc/bstr.go diff --git a/chain/blockvalidator.go b/chain/blockvalidator.go index 3fa07fb91..24c12add7 100644 --- a/chain/blockvalidator.go +++ b/chain/blockvalidator.go @@ -90,7 +90,7 @@ func (t validateReport) toString() string { result = "failed" } - msgStr = fmt.Sprintf("%s : %s. block= %s, computed=%s", t.name, result, enc.ToString(t.src), enc.ToString(t.target)) + msgStr = fmt.Sprintf("%s : %s. block= %s, computed=%s", t.name, result, enc.B58Encode(t.src), enc.B58Encode(t.target)) return msgStr } @@ -99,7 +99,7 @@ func (bv *BlockValidator) ValidateBody(block *types.Block) error { txs := block.GetBody().GetTxs() // TxRootHash - logger.Debug().Int("Txlen", len(txs)).Str("TxRoot", enc.ToString(block.GetHeader().GetTxsRootHash())). + logger.Debug().Int("Txlen", len(txs)).Str("TxRoot", enc.B58Encode(block.GetHeader().GetTxsRootHash())). Msg("tx root verify") hdrRootHash := block.GetHeader().GetTxsRootHash() @@ -112,8 +112,8 @@ func (bv *BlockValidator) ValidateBody(block *types.Block) error { if !ret { logger.Error().Str("block", block.ID()). - Str("txroot", enc.ToString(hdrRootHash)). - Str("compute txroot", enc.ToString(computeTxRootHash)). + Str("txroot", enc.B58Encode(hdrRootHash)). + Str("compute txroot", enc.B58Encode(computeTxRootHash)). Msg("tx root validation failed") return ErrorBlockVerifyTxRoot @@ -160,13 +160,13 @@ func (bv *BlockValidator) ValidatePost(sdbRoot []byte, receipts *types.Receipts, } if !ret { logger.Error().Str("block", block.ID()). - Str("hdrroot", enc.ToString(hdrRoot)). - Str("sdbroot", enc.ToString(sdbRoot)). + Str("hdrroot", enc.B58Encode(hdrRoot)). + Str("sdbroot", enc.B58Encode(sdbRoot)). Msg("block root hash validation failed") return ErrorBlockVerifyStateRoot } - logger.Debug().Str("sdbroot", enc.ToString(sdbRoot)). + logger.Debug().Str("sdbroot", enc.B58Encode(sdbRoot)). Msg("block root hash validation succeed") hdrRoot = block.GetHeader().ReceiptsRootHash @@ -177,12 +177,12 @@ func (bv *BlockValidator) ValidatePost(sdbRoot []byte, receipts *types.Receipts, bv.report(validateReport{name: "Verify receipt merkle root", pass: ret, src: hdrRoot, target: receiptsRoot}) } else if !ret { logger.Error().Str("block", block.ID()). - Str("hdrroot", enc.ToString(hdrRoot)). - Str("receipts_root", enc.ToString(receiptsRoot)). + Str("hdrroot", enc.B58Encode(hdrRoot)). + Str("receipts_root", enc.B58Encode(receiptsRoot)). Msg("receipts root hash validation failed") return ErrorBlockVerifyReceiptRoot } - logger.Debug().Str("receipts_root", enc.ToString(receiptsRoot)). + logger.Debug().Str("receipts_root", enc.B58Encode(receiptsRoot)). Msg("receipt root hash validation succeed") return nil diff --git a/chain/chainanchor.go b/chain/chainanchor.go index a29455879..5cb88c71a 100644 --- a/chain/chainanchor.go +++ b/chain/chainanchor.go @@ -72,7 +72,7 @@ func (cs *ChainService) getAnchorsFromHash(blockHash []byte) ChainAnchor { return nil } - logger.Debug().Uint64("no", latestNo).Str("hash", enc.ToString(blockHash)).Msg("anchor") + logger.Debug().Uint64("no", latestNo).Str("hash", enc.B58Encode(blockHash)).Msg("anchor") anchors = append(anchors, blockHash) if latestNo == 0 { @@ -91,7 +91,7 @@ func (cs *ChainService) getAnchorsFromHash(blockHash []byte) ChainAnchor { return nil } - logger.Debug().Uint64("no", latestNo).Str("hash", enc.ToString(blockHash)).Msg("anchor") + logger.Debug().Uint64("no", latestNo).Str("hash", enc.B58Encode(blockHash)).Msg("anchor") anchors = append(anchors, blockHash) if latestNo <= dec { diff --git a/chain/chaindb.go b/chain/chaindb.go index a846444cd..6c8823bfa 100644 --- a/chain/chaindb.go +++ b/chain/chaindb.go @@ -7,7 +7,6 @@ package chain import ( "bytes" - "encoding/gob" "encoding/json" "errors" "fmt" @@ -45,7 +44,7 @@ func (e ErrNoBlock) Error() string { switch id := e.id.(type) { case []byte: - idStr = fmt.Sprintf("blockHash=%v", enc.ToString(id)) + idStr = fmt.Sprintf("blockHash=%v", enc.B58Encode(id)) default: idStr = fmt.Sprintf("blockNo=%v", id) } @@ -445,7 +444,7 @@ func (cdb *ChainDB) addTxsOfBlock(dbTx *db.Transaction, txs []*types.Tx, blockHa for i, txEntry := range txs { if err := cdb.addTx(dbTx, txEntry, blockHash, i); err != nil { - logger.Error().Err(err).Str("hash", enc.ToString(blockHash)).Int("txidx", i). + logger.Error().Err(err).Str("hash", enc.B58Encode(blockHash)).Int("txidx", i). Msg("failed to add tx") return err @@ -611,7 +610,7 @@ func (cdb *ChainDB) getTx(txHash []byte) (*types.Tx, *types.TxIdx, error) { err := cdb.loadData(txHash, txIdx) if err != nil { - return nil, nil, fmt.Errorf("tx not found: txHash=%v", enc.ToString(txHash)) + return nil, nil, fmt.Errorf("tx not found: txHash=%v", enc.B58Encode(txHash)) } block, err := cdb.getBlock(txIdx.BlockHash) if err != nil { @@ -622,7 +621,7 @@ func (cdb *ChainDB) getTx(txHash []byte) (*types.Tx, *types.TxIdx, error) { return nil, nil, fmt.Errorf("wrong tx idx: %d", txIdx.Idx) } tx := txs[txIdx.Idx] - logger.Debug().Str("hash", enc.ToString(txHash)).Msg("getTx") + logger.Debug().Str("hash", enc.B58Encode(txHash)).Msg("getTx") return tx, txIdx, nil } @@ -649,13 +648,10 @@ func (cdb *ChainDB) getReceipts(blockHash []byte, blockNo types.BlockNo, if len(data) == 0 { return nil, errors.New("cannot find a receipt") } - var b bytes.Buffer - b.Write(data) var receipts types.Receipts receipts.SetHardFork(hardForkConfig, blockNo) - decoder := gob.NewDecoder(&b) - err := decoder.Decode(&receipts) + err := common.GobDecode(data, &receipts) return &receipts, err } @@ -683,9 +679,9 @@ func (cdb *ChainDB) GetChainTree() ([]byte, error) { hash, _ := cdb.getHashByNo(i) tree = append(tree, ChainInfo{ Height: i, - Hash: enc.ToString(hash), + Hash: enc.B58Encode(hash), }) - logger.Info().Str("hash", enc.ToString(hash)).Msg("GetChainTree") + logger.Info().Str("hash", enc.B58Encode(hash)).Msg("GetChainTree") } jsonBytes, err := json.Marshal(tree) if err != nil { @@ -698,11 +694,8 @@ func (cdb *ChainDB) writeReceipts(blockHash []byte, blockNo types.BlockNo, recei dbTx := cdb.store.NewTx() defer dbTx.Discard() - var val bytes.Buffer - gobEncoder := gob.NewEncoder(&val) - gobEncoder.Encode(receipts) - - dbTx.Set(dbkey.Receipts(blockHash, blockNo), val.Bytes()) + val, _ := common.GobEncode(receipts) + dbTx.Set(dbkey.Receipts(blockHash, blockNo), val) dbTx.Commit() } @@ -743,10 +736,7 @@ func (cdb *ChainDB) getReorgMarker() (*ReorgMarker, error) { } var marker ReorgMarker - var b bytes.Buffer - b.Write(data) - decoder := gob.NewDecoder(&b) - err := decoder.Decode(&marker) + err := common.GobDecode(data, &marker) return &marker, err } diff --git a/chain/chaindbForRaft.go b/chain/chaindbForRaft.go index 49d71c045..21b0da75e 100644 --- a/chain/chaindbForRaft.go +++ b/chain/chaindbForRaft.go @@ -1,12 +1,11 @@ package chain import ( - "bytes" - "encoding/gob" "errors" "github.com/aergoio/aergo-lib/db" "github.com/aergoio/aergo/v2/consensus" + "github.com/aergoio/aergo/v2/internal/common" "github.com/aergoio/aergo/v2/types" "github.com/aergoio/aergo/v2/types/dbkey" "github.com/aergoio/etcd/raft/raftpb" @@ -235,10 +234,7 @@ func (cdb *ChainDB) GetRaftEntry(idx uint64) (*consensus.WalEntry, error) { } var entry consensus.WalEntry - var b bytes.Buffer - b.Write(data) - decoder := gob.NewDecoder(&b) - if err := decoder.Decode(&entry); err != nil { + if err := common.GobDecode(data, &entry); err != nil { return nil, err } @@ -425,14 +421,12 @@ func (cdb *ChainDB) WriteIdentity(identity *consensus.RaftIdentity) error { logger.Info().Str("id", identity.ToString()).Msg("save raft identity") - var val bytes.Buffer - - enc := gob.NewEncoder(&val) - if err := enc.Encode(identity); err != nil { + enc, err := common.GobEncode(identity) + if err != nil { return ErrEncodeRaftIdentity } - dbTx.Set(dbkey.RaftIdentity(), val.Bytes()) + dbTx.Set(dbkey.RaftIdentity(), enc) dbTx.Commit() return nil @@ -445,10 +439,7 @@ func (cdb *ChainDB) GetIdentity() (*consensus.RaftIdentity, error) { } var id consensus.RaftIdentity - var b bytes.Buffer - b.Write(data) - decoder := gob.NewDecoder(&b) - if err := decoder.Decode(&id); err != nil { + if err := common.GobDecode(data, &id); err != nil { return nil, ErrDecodeRaftIdentity } diff --git a/chain/chainhandle.go b/chain/chainhandle.go index 70024bffe..a76eacb85 100644 --- a/chain/chainhandle.go +++ b/chain/chainhandle.go @@ -55,7 +55,7 @@ type ErrBlock struct { } func (ec *ErrBlock) Error() string { - return fmt.Sprintf("Error: %s. block(%s, %d)", ec.err.Error(), enc.ToString(ec.block.Hash), ec.block.No) + return fmt.Sprintf("Error: %s. block(%s, %d)", ec.err.Error(), enc.B58Encode(ec.block.Hash), ec.block.No) } type ErrTx struct { @@ -64,7 +64,7 @@ type ErrTx struct { } func (ec *ErrTx) Error() string { - return fmt.Sprintf("error executing tx:%s, tx=%s", ec.err.Error(), enc.ToString(ec.tx.GetHash())) + return fmt.Sprintf("error executing tx:%s, tx=%s", ec.err.Error(), enc.B58Encode(ec.tx.GetHash())) } func (cs *ChainService) getBestBlockNo() types.BlockNo { @@ -288,7 +288,7 @@ func (cp *chainProcessor) addBlock(blk *types.Block) error { Uint64("latest", cp.cdb.getBestBlockNo()). Uint64("blockNo", blk.BlockNo()). Str("hash", blk.ID()). - Str("prev_hash", enc.ToString(blk.GetHeader().GetPrevBlockHash())). + Str("prev_hash", enc.B58Encode(blk.GetHeader().GetPrevBlockHash())). Msg("block added to the block indices") } cp.lastBlock = blk @@ -637,7 +637,7 @@ func NewTxExecutor(execCtx context.Context, ccc consensus.ChainConsensusCluster, err := executeTx(execCtx, ccc, cdb, bState, tx, bi, preloadService) if err != nil { - logger.Error().Err(err).Str("hash", enc.ToString(tx.GetHash())).Msg("tx failed") + logger.Error().Err(err).Str("hash", enc.B58Encode(tx.GetHash())).Msg("tx failed") if err2 := bState.Rollback(blockSnap); err2 != nil { logger.Panic().Err(err).Msg("failed to rollback block state") } @@ -949,7 +949,7 @@ func executeTx(execCtx context.Context, ccc consensus.ChainConsensusCluster, cdb txFee = new(big.Int).SetUint64(0) events, err = executeGovernanceTx(ccc, bs, txBody, sender, receiver, bi) if err != nil { - logger.Warn().Err(err).Str("txhash", enc.ToString(tx.GetHash())).Msg("governance tx Error") + logger.Warn().Err(err).Str("txhash", enc.B58Encode(tx.GetHash())).Msg("governance tx Error") } case types.TxType_FEEDELEGATION: balance := receiver.Balance() @@ -970,7 +970,7 @@ func executeTx(execCtx context.Context, ccc consensus.ChainConsensusCluster, cdb tx.GetHash(), txBody.GetAccount(), txBody.GetAmount()) if err != nil { if err != types.ErrNotAllowedFeeDelegation { - logger.Warn().Err(err).Str("txhash", enc.ToString(tx.GetHash())).Msg("checkFeeDelegation Error") + logger.Warn().Err(err).Str("txhash", enc.B58Encode(tx.GetHash())).Msg("checkFeeDelegation Error") return err } return types.ErrNotAllowedFeeDelegation diff --git a/chain/chainservice.go b/chain/chainservice.go index 3504758b3..b7fb7e3b3 100644 --- a/chain/chainservice.go +++ b/chain/chainservice.go @@ -145,7 +145,7 @@ func (core *Core) initGenesis(genesis *types.Genesis, mainnet bool, testmode boo genesisBlock, _ := core.cdb.GetBlockByNo(0) logger.Info().Str("chain id", gen.ID.ToJSON()). - Str("hash", enc.ToString(genesisBlock.GetHash())).Msg("chain initialized") + Str("hash", enc.B58Encode(genesisBlock.GetHash())).Msg("chain initialized") return genesisBlock, nil } @@ -274,7 +274,7 @@ func NewChainService(cfg *cfg.Config) *ChainService { logger.Debug().Err(err).Msg("failed to get elected BPs") } else { for _, res := range top.Votes { - logger.Debug().Str("BP", enc.ToString(res.Candidate)). + logger.Debug().Str("BP", enc.B58Encode(res.Candidate)). Str("votes", new(big.Int).SetBytes(res.Amount).String()).Msgf("BP vote stat") } } @@ -641,7 +641,7 @@ func (cm *ChainManager) Receive(context actor.Context) { bstate = msg.Bstate.(*state.BlockState) if timeoutTx := bstate.TimeoutTx(); timeoutTx != nil { if logger.IsDebugEnabled() { - logger.Debug().Str("hash", enc.ToString(timeoutTx.GetHash())).Msg("received timeout tx") + logger.Debug().Str("hash", enc.B58Encode(timeoutTx.GetHash())).Msg("received timeout tx") } cm.TellTo(message.MemPoolSvc, &message.MemPoolDelTx{Tx: timeoutTx.GetTx()}) } @@ -686,7 +686,7 @@ func getAddressNameResolved(sdb *state.StateDB, account []byte) ([]byte, error) if len(account) == types.NameLength { scs, err := sdb.GetNameAccountState() if err != nil { - logger.Error().Str("hash", enc.ToString(account)).Err(err).Msg("failed to get state for account") + logger.Error().Str("hash", enc.B58Encode(account)).Err(err).Msg("failed to get state for account") return nil, err } return name.GetAddress(scs, account), nil @@ -705,7 +705,7 @@ func (cw *ChainWorker) Receive(context actor.Context) { id := types.ToAccountID(address) proof, err := sdb.GetAccountAndProof(id[:], root, compressed) if err != nil { - logger.Error().Str("hash", enc.ToString(address)).Err(err).Msg("failed to get state for account") + logger.Error().Str("hash", enc.B58Encode(address)).Err(err).Msg("failed to get state for account") return nil, err } proof.Key = address @@ -717,7 +717,7 @@ func (cw *ChainWorker) Receive(context actor.Context) { bid := types.ToBlockID(msg.BlockHash) block, err := cw.getBlock(bid[:]) if err != nil { - logger.Debug().Err(err).Str("hash", enc.ToString(msg.BlockHash)).Msg("block not found") + logger.Debug().Err(err).Str("hash", enc.B58Encode(msg.BlockHash)).Msg("block not found") } context.Respond(message.GetBlockRsp{ Block: block, @@ -746,7 +746,7 @@ func (cw *ChainWorker) Receive(context actor.Context) { id := types.ToAccountID(address) accState, err := sdb.GetAccountState(id) if err != nil { - logger.Error().Str("hash", enc.ToString(address)).Err(err).Msg("failed to get state for account") + logger.Error().Str("hash", enc.B58Encode(address)).Err(err).Msg("failed to get state for account") } context.Respond(message.GetStateRsp{ Account: address, @@ -807,7 +807,7 @@ func (cw *ChainWorker) Receive(context actor.Context) { } ctrState, err := sdb.OpenContractStateAccount(types.ToAccountID(address)) if err != nil { - logger.Error().Str("hash", enc.ToString(address)).Err(err).Msg("failed to get state for contract") + logger.Error().Str("hash", enc.B58Encode(address)).Err(err).Msg("failed to get state for contract") context.Respond(message.GetQueryRsp{Result: nil, Err: err}) } else { bs := state.NewBlockState(sdb) @@ -833,7 +833,7 @@ func (cw *ChainWorker) Receive(context actor.Context) { varProof.Key = storageKey varProofs = append(varProofs, varProof) if err != nil { - logger.Error().Str("hash", enc.ToString(contractProof.Key)).Err(err).Msg("failed to get state variable in contract") + logger.Error().Str("hash", enc.B58Encode(contractProof.Key)).Err(err).Msg("failed to get state variable in contract") } } } @@ -895,7 +895,7 @@ func (cw *ChainWorker) Receive(context actor.Context) { sdb = cw.sdb.OpenNewStateDB(cw.sdb.GetRoot()) ctrState, err := sdb.OpenContractStateAccount(types.ToAccountID(msg.Contract)) if err != nil { - logger.Error().Str("hash", enc.ToString(msg.Contract)).Err(err).Msg("failed to get state for contract") + logger.Error().Str("hash", enc.B58Encode(msg.Contract)).Err(err).Msg("failed to get state for contract") context.Respond(message.CheckFeeDelegationRsp{Err: err}) } else { bs := state.NewBlockState(sdb) diff --git a/chain/chainverifier.go b/chain/chainverifier.go index bd5bc4fc2..3fd86bfb3 100644 --- a/chain/chainverifier.go +++ b/chain/chainverifier.go @@ -189,14 +189,14 @@ func (cv *ChainVerifier) report(prevBlock *types.Block, targetBlock *types.Block switch cv.stage { case TestPrevBlock: report += fmt.Sprintf("[description] prev block hash=%s, prev stage root=%s", prevBlock.ID(), - enc.ToString(prevBlock.GetHeader().GetBlocksRootHash())) + enc.B58Encode(prevBlock.GetHeader().GetBlocksRootHash())) case TestCurBlock: report += fmt.Sprintf("[description] target block hash=%s", targetBlock.ID()) case TestBlockExecute: - report += fmt.Sprintf("[description] tx Merkle = %s", enc.ToString(targetBlock.GetHeader().GetTxsRootHash())) - report += fmt.Sprintf(", state Root = %s", enc.ToString(targetBlock.GetHeader().GetBlocksRootHash())) + report += fmt.Sprintf("[description] tx Merkle = %s", enc.B58Encode(targetBlock.GetHeader().GetTxsRootHash())) + report += fmt.Sprintf(", state Root = %s", enc.B58Encode(targetBlock.GetHeader().GetBlocksRootHash())) report += fmt.Sprintf(", all transaction passed") } diff --git a/chain/common.go b/chain/common.go index fccd0ec9c..1556a48d8 100644 --- a/chain/common.go +++ b/chain/common.go @@ -48,7 +48,7 @@ func Init(maxBlkBodySize uint32, coinbaseAccountStr string, isBp bool, maxAnchor if err != nil { return ErrInvalidCoinbaseAccount } - logger.Info().Str("account", enc.ToString(CoinbaseAccount)).Str("str", coinbaseAccountStr). + logger.Info().Str("account", enc.B58Encode(CoinbaseAccount)).Str("str", coinbaseAccountStr). Msg("set coinbase account") } else { diff --git a/chain/orphanpool.go b/chain/orphanpool.go index 1e254fcb7..edc79749a 100644 --- a/chain/orphanpool.go +++ b/chain/orphanpool.go @@ -51,7 +51,7 @@ func NewOrphanPool(size int) *OrphanPool { // add Orphan into the orphan cache pool func (op *OrphanPool) addOrphan(block *types.Block) error { - logger.Warn().Str("prev", enc.ToString(block.GetHeader().GetPrevBlockHash())).Msg("add orphan Block") + logger.Warn().Str("prev", enc.B58Encode(block.GetHeader().GetPrevBlockHash())).Msg("add orphan Block") id := types.ToBlockID(block.Header.PrevBlockHash) cachedblock, exists := op.cache[id] diff --git a/chain/recover.go b/chain/recover.go index af70d54de..63a99bdc1 100644 --- a/chain/recover.go +++ b/chain/recover.go @@ -2,13 +2,13 @@ package chain import ( "bytes" - "encoding/gob" "errors" "fmt" "os" "runtime" "runtime/debug" + "github.com/aergoio/aergo/v2/internal/common" "github.com/aergoio/aergo/v2/internal/enc" "github.com/aergoio/aergo/v2/types" "github.com/aergoio/aergo/v2/types/dbkey" @@ -63,7 +63,7 @@ func (cs *ChainService) Recover() error { // check status of chain if !bytes.Equal(best.BlockHash(), marker.BrBestHash) { - logger.Error().Str("best", best.ID()).Str("markerbest", enc.ToString(marker.BrBestHash)).Msg("best block is not equal to old chain") + logger.Error().Str("best", best.ID()).Str("markerbest", enc.B58Encode(marker.BrBestHash)).Msg("best block is not equal to old chain") return ErrRecoInvalidBest } @@ -218,26 +218,20 @@ func (rm *ReorgMarker) delete() { } func (rm *ReorgMarker) toBytes() ([]byte, error) { - var val bytes.Buffer - encoder := gob.NewEncoder(&val) - if err := encoder.Encode(rm); err != nil { - return nil, err - } - - return val.Bytes(), nil + return common.GobEncode(rm) } func (rm *ReorgMarker) toString() string { buf := "" if len(rm.BrStartHash) != 0 { - buf = buf + fmt.Sprintf("branch root=(%d, %s).", rm.BrStartNo, enc.ToString(rm.BrStartHash)) + buf = buf + fmt.Sprintf("branch root=(%d, %s).", rm.BrStartNo, enc.B58Encode(rm.BrStartHash)) } if len(rm.BrTopHash) != 0 { - buf = buf + fmt.Sprintf("branch top=(%d, %s).", rm.BrTopNo, enc.ToString(rm.BrTopHash)) + buf = buf + fmt.Sprintf("branch top=(%d, %s).", rm.BrTopNo, enc.B58Encode(rm.BrTopHash)) } if len(rm.BrBestHash) != 0 { - buf = buf + fmt.Sprintf("org best=(%d, %s).", rm.BrBestNo, enc.ToString(rm.BrBestHash)) + buf = buf + fmt.Sprintf("org best=(%d, %s).", rm.BrBestNo, enc.B58Encode(rm.BrBestHash)) } return buf diff --git a/chain/reorg.go b/chain/reorg.go index 53ce6f3d2..91dc1c636 100644 --- a/chain/reorg.go +++ b/chain/reorg.go @@ -52,7 +52,7 @@ type ErrReorgBlock struct { func (ec *ErrReorgBlock) Error() string { if ec.blockHash != nil { - return fmt.Sprintf("%s, block:%d,%s", ec.msg, ec.blockNo, enc.ToString(ec.blockHash)) + return fmt.Sprintf("%s, block:%d,%s", ec.msg, ec.blockNo, enc.B58Encode(ec.blockHash)) } else if ec.blockNo != 0 { return fmt.Sprintf("%s, block:%d", ec.msg, ec.blockNo) } else { diff --git a/chain/signVerifier.go b/chain/signVerifier.go index b3b65edab..304b12fae 100644 --- a/chain/signVerifier.go +++ b/chain/signVerifier.go @@ -83,7 +83,7 @@ func (sv *SignVerifier) verifyTxLoop(workerNo int) { hit, err := sv.verifyTx(sv.comm, txWork.tx, txWork.useMempool) if err != nil { - logger.Error().Int("worker", workerNo).Bool("hit", hit).Str("hash", enc.ToString(txWork.tx.GetHash())). + logger.Error().Int("worker", workerNo).Bool("hit", hit).Str("hash", enc.B58Encode(txWork.tx.GetHash())). Err(err).Msg("error verify tx") } diff --git a/cmd/aergocli/cmd/blockchain_test.go b/cmd/aergocli/cmd/blockchain_test.go index 112fb0dc2..5f271a310 100644 --- a/cmd/aergocli/cmd/blockchain_test.go +++ b/cmd/aergocli/cmd/blockchain_test.go @@ -5,9 +5,9 @@ import ( "testing" "github.com/aergoio/aergo/v2/cmd/aergocli/util/encoding/json" + "github.com/aergoio/aergo/v2/internal/enc" "github.com/aergoio/aergo/v2/types" "github.com/golang/mock/gomock" - "github.com/mr-tron/base58/base58" "github.com/stretchr/testify/assert" ) @@ -16,7 +16,7 @@ func TestBlockchainWithMock(t *testing.T) { defer deinitMock() testBlockHashString := "56Qy6MQei9KM13rqEq1jiJ7Da21Kcq9KdmYWcnPLtxS3" - testBlockHash, _ := base58.Decode(testBlockHashString) + testBlockHash, _ := enc.B58Decode(testBlockHashString) mock.EXPECT().Blockchain( gomock.Any(), // expect any value for first parameter @@ -48,7 +48,7 @@ func TestBlockchainWithMock(t *testing.T) { if err := json.Unmarshal([]byte(output), &result); err != nil { t.Fatal(err) } - testBlockHashByte, _ := base58.Decode(testBlockHashString) + testBlockHashByte, _ := enc.B58Decode(testBlockHashString) assert.Equal(t, hex.EncodeToString(testBlockHashByte), result["Hash"]) assert.Equal(t, float64(1), result["Height"]) } diff --git a/cmd/aergocli/cmd/committx_test.go b/cmd/aergocli/cmd/committx_test.go index 27f3de136..4259cebf9 100644 --- a/cmd/aergocli/cmd/committx_test.go +++ b/cmd/aergocli/cmd/committx_test.go @@ -4,9 +4,9 @@ import ( "testing" "github.com/aergoio/aergo/v2/cmd/aergocli/util/encoding/json" + "github.com/aergoio/aergo/v2/internal/enc" "github.com/aergoio/aergo/v2/types" "github.com/golang/mock/gomock" - "github.com/mr-tron/base58/base58" "github.com/stretchr/testify/assert" ) @@ -15,7 +15,7 @@ func TestCommitTxWithMock(t *testing.T) { defer deinitMock() testTxHashString := "HB44gJvHhVoEfgiGq3VZmV9VUXfBXhHjcEvroBMkJGnY" - testTxHash, _ := base58.Decode(testTxHashString) + testTxHash, _ := enc.B58Decode(testTxHashString) output, err := executeCommand(rootCmd, "committx", "--jsontx", "{}") assert.Error(t, err, "should occur error when empty json") @@ -56,5 +56,5 @@ func TestCommitTxWithMock(t *testing.T) { output, err = executeCommand(rootCmd, "committx", "--jsontx", "{ \"Hash\": \"HB44gJvHhVoEfgiGq3VZmV9VUXfBXhHjcEvroBMkJGnY\", \"Body\": {\"Nonce\": 2, \"Account\": \"AmNBZ8WQKP8DbuP9Q9W9vGFhiT8vQNcuSZ2SbBbVvbJWGV3Wh1mn\", \"Recipient\": \"AmLnVfGwq49etaa7dnzfGJTbaZWV7aVmrxFes4KmWukXwtooVZPJ\", \"Amount\": \"25000\", \"Payload\": \"\", \"Limit\": 100, \"Price\": \"1\", \"Type\": 0, \"Sign\": \"381yXYxTtq2tRPRQPF7tHH6Cq3y8PvcsFWztPwCRmmYfqnK83Z3a6Yj9fyy8Rpvrrw76Y52SNAP6Th3BYQjX1Bcmf6NQrDHQ\"}}") err = json.Unmarshal([]byte(output), out) assert.NoError(t, err, "should no error") - assert.Equal(t, "HB44gJvHhVoEfgiGq3VZmV9VUXfBXhHjcEvroBMkJGnY", base58.Encode(out.GetResults()[0].Hash)) + assert.Equal(t, "HB44gJvHhVoEfgiGq3VZmV9VUXfBXhHjcEvroBMkJGnY", enc.B58Encode(out.GetResults()[0].Hash)) } diff --git a/cmd/aergocli/cmd/contract.go b/cmd/aergocli/cmd/contract.go index 0e8bbb2aa..7a76698a6 100644 --- a/cmd/aergocli/cmd/contract.go +++ b/cmd/aergocli/cmd/contract.go @@ -14,9 +14,9 @@ import ( luacEncoding "github.com/aergoio/aergo/v2/cmd/aergoluac/encoding" luac "github.com/aergoio/aergo/v2/cmd/aergoluac/util" "github.com/aergoio/aergo/v2/internal/common" + "github.com/aergoio/aergo/v2/internal/enc" "github.com/aergoio/aergo/v2/types" aergorpc "github.com/aergoio/aergo/v2/types" - "github.com/mr-tron/base58/base58" "github.com/spf13/cobra" ) @@ -311,7 +311,7 @@ func runCallCmd(cmd *cobra.Command, args []string) error { } if chainIdHash != "" { - rawCidHash, err := base58.Decode(chainIdHash) + rawCidHash, err := enc.B58Decode(chainIdHash) if err != nil { return fmt.Errorf("failed to parse chainidhash: %v", err.Error()) } @@ -414,7 +414,7 @@ func runQueryStateCmd(cmd *cobra.Command, args []string) error { return fmt.Errorf("failed to decode address: %v", err.Error()) } if len(stateroot) != 0 { - root, err = base58.Decode(stateroot) + root, err = enc.B58Decode(stateroot) if err != nil { return fmt.Errorf("failed to decode stateroot: %v", err.Error()) } diff --git a/cmd/aergocli/cmd/enterprise.go b/cmd/aergocli/cmd/enterprise.go index ad24bfd40..f9d280428 100644 --- a/cmd/aergocli/cmd/enterprise.go +++ b/cmd/aergocli/cmd/enterprise.go @@ -16,9 +16,9 @@ import ( "github.com/aergoio/aergo/v2/cmd/aergocli/util" "github.com/aergoio/aergo/v2/cmd/aergocli/util/encoding/json" "github.com/aergoio/aergo/v2/contract/enterprise" + "github.com/aergoio/aergo/v2/internal/enc" "github.com/aergoio/aergo/v2/types" aergorpc "github.com/aergoio/aergo/v2/types" - "github.com/mr-tron/base58/base58" "github.com/spf13/cobra" ) @@ -155,7 +155,7 @@ var enterpriseTxCmd = &cobra.Command{ Short: "Print transaction for enterprise", Args: cobra.MinimumNArgs(1), Run: func(cmd *cobra.Command, args []string) { - txHashDecode, err := base58.Decode(args[0]) + txHashDecode, err := enc.B58Decode(args[0]) if err != nil { cmd.Println("Failed: invalid tx hash") return diff --git a/cmd/aergocli/cmd/enterprise_test.go b/cmd/aergocli/cmd/enterprise_test.go index 09737e07b..139698026 100644 --- a/cmd/aergocli/cmd/enterprise_test.go +++ b/cmd/aergocli/cmd/enterprise_test.go @@ -5,9 +5,9 @@ import ( "errors" "testing" + "github.com/aergoio/aergo/v2/internal/enc" aergorpc "github.com/aergoio/aergo/v2/types" "github.com/golang/mock/gomock" - "github.com/mr-tron/base58/base58" "github.com/stretchr/testify/assert" ) @@ -17,9 +17,9 @@ func TestGetConfChangeWithMock(t *testing.T) { var ( testTxHashString = "HB44gJvHhVoEfgiGq3VZmV9VUXfBXhHjcEvroBMkJGnY" - testTxHash, _ = base58.Decode(testTxHashString) + testTxHash, _ = enc.B58Decode(testTxHashString) testBlockHashString = "56Qy6MQei9KM13rqEq1jiJ7Da21Kcq9KdmYWcnPLtxS3" - testBlockHash, _ = base58.Decode(testBlockHashString) + testBlockHash, _ = enc.B58Decode(testBlockHashString) tx *aergorpc.Tx = &aergorpc.Tx{Hash: testTxHash, Body: &aergorpc.TxBody{Payload: []byte(string("{ \"name\": \"GetConfTest\" }"))}} resTxInBlock *aergorpc.TxInBlock = &aergorpc.TxInBlock{TxIdx: &aergorpc.TxIdx{BlockHash: testBlockHash, Idx: 1}, Tx: tx} diff --git a/cmd/aergocli/cmd/getblock.go b/cmd/aergocli/cmd/getblock.go index 6f29340b0..f2c0d86c3 100644 --- a/cmd/aergocli/cmd/getblock.go +++ b/cmd/aergocli/cmd/getblock.go @@ -12,8 +12,8 @@ import ( "fmt" "github.com/aergoio/aergo/v2/cmd/aergocli/util" + "github.com/aergoio/aergo/v2/internal/enc" aergorpc "github.com/aergoio/aergo/v2/types" - "github.com/mr-tron/base58/base58" "github.com/spf13/cobra" ) @@ -56,7 +56,7 @@ func getSingleBlock(cmd *cobra.Command) error { binary.LittleEndian.PutUint64(b, uint64(number)) blockQuery = b } else { - decoded, err := base58.Decode(hash) + decoded, err := enc.B58Decode(hash) if err != nil { return fmt.Errorf("failed to decode block hash: %v", err) } diff --git a/cmd/aergocli/cmd/getstate.go b/cmd/aergocli/cmd/getstate.go index a2b02c3eb..e39be0775 100644 --- a/cmd/aergocli/cmd/getstate.go +++ b/cmd/aergocli/cmd/getstate.go @@ -9,8 +9,8 @@ import ( "context" "github.com/aergoio/aergo/v2/cmd/aergocli/util" + "github.com/aergoio/aergo/v2/internal/enc" "github.com/aergoio/aergo/v2/types" - "github.com/mr-tron/base58/base58" "github.com/spf13/cobra" ) @@ -35,7 +35,7 @@ func execGetState(cmd *cobra.Command, args []string) { var root []byte var err error if len(stateroot) != 0 { - root, err = base58.Decode(stateroot) + root, err = enc.B58Decode(stateroot) if err != nil { cmd.Printf("decode error: %s", err.Error()) return diff --git a/cmd/aergocli/cmd/gettx.go b/cmd/aergocli/cmd/gettx.go index a9f7f8d8e..3013d450e 100644 --- a/cmd/aergocli/cmd/gettx.go +++ b/cmd/aergocli/cmd/gettx.go @@ -9,8 +9,8 @@ import ( "context" "github.com/aergoio/aergo/v2/cmd/aergocli/util" + "github.com/aergoio/aergo/v2/internal/enc" aergorpc "github.com/aergoio/aergo/v2/types" - "github.com/mr-tron/base58/base58" "github.com/spf13/cobra" ) @@ -30,7 +30,7 @@ func init() { } func execGetTX(cmd *cobra.Command, args []string) { - txHash, err := base58.Decode(args[0]) + txHash, err := enc.B58Decode(args[0]) if err != nil { cmd.Printf("Failed decode: %s", err.Error()) return diff --git a/cmd/aergocli/cmd/keygen.go b/cmd/aergocli/cmd/keygen.go index 8d6a323e9..6a26be7f8 100644 --- a/cmd/aergocli/cmd/keygen.go +++ b/cmd/aergocli/cmd/keygen.go @@ -1,7 +1,6 @@ package cmd import ( - b64 "encoding/base64" "encoding/json" "fmt" "os" @@ -10,6 +9,7 @@ import ( "github.com/aergoio/aergo/v2/account/key" keycrypto "github.com/aergoio/aergo/v2/account/key/crypto" + "github.com/aergoio/aergo/v2/internal/enc" "github.com/aergoio/aergo/v2/p2p/p2putil" "github.com/aergoio/aergo/v2/types" "github.com/btcsuite/btcd/btcec" @@ -195,7 +195,7 @@ func generateKeyJson(priv crypto.PrivKey, pub crypto.PubKey) error { addressEncoded := types.EncodeAddress(address) jsonMarshalled, err := json.MarshalIndent(keyJson{ Address: addressEncoded, - PubKey: b64.StdEncoding.EncodeToString(pubBytes), + PubKey: enc.B64Encode(pubBytes), PrivKey: types.EncodePrivKey(privKeyExport), Id: types.IDB58Encode(pid), }, "", " ") diff --git a/cmd/aergocli/cmd/listblocks.go b/cmd/aergocli/cmd/listblocks.go index d20a32385..bc1b4dc0c 100644 --- a/cmd/aergocli/cmd/listblocks.go +++ b/cmd/aergocli/cmd/listblocks.go @@ -9,8 +9,8 @@ import ( "context" "github.com/aergoio/aergo/v2/cmd/aergocli/util" + "github.com/aergoio/aergo/v2/internal/enc" "github.com/aergoio/aergo/v2/types" - "github.com/mr-tron/base58/base58" "github.com/spf13/cobra" ) @@ -41,7 +41,7 @@ func execListBlockHeaders(cmd *cobra.Command, args []string) { var err error if cmd.Flags().Changed("hash") == true { - blockHash, err = base58.Decode(gbhHash) + blockHash, err = enc.B58Decode(gbhHash) if err != nil { cmd.Printf("Failed: %s", err.Error()) return diff --git a/cmd/aergocli/cmd/receipt.go b/cmd/aergocli/cmd/receipt.go index fc7d8fefe..4b8c207eb 100644 --- a/cmd/aergocli/cmd/receipt.go +++ b/cmd/aergocli/cmd/receipt.go @@ -10,8 +10,8 @@ import ( "log" "github.com/aergoio/aergo/v2/cmd/aergocli/util" + "github.com/aergoio/aergo/v2/internal/enc" aergorpc "github.com/aergoio/aergo/v2/types" - "github.com/mr-tron/base58/base58" "github.com/spf13/cobra" ) @@ -28,7 +28,7 @@ func init() { Short: "Get a receipt", Args: cobra.MinimumNArgs(1), Run: func(cmd *cobra.Command, args []string) { - txHash, err := base58.Decode(args[0]) + txHash, err := enc.B58Decode(args[0]) if err != nil { log.Fatal(err) } diff --git a/cmd/aergocli/cmd/sendtx.go b/cmd/aergocli/cmd/sendtx.go index f76923ba7..9bd3f8b09 100644 --- a/cmd/aergocli/cmd/sendtx.go +++ b/cmd/aergocli/cmd/sendtx.go @@ -10,8 +10,8 @@ import ( "errors" "github.com/aergoio/aergo/v2/cmd/aergocli/util" + "github.com/aergoio/aergo/v2/internal/enc" "github.com/aergoio/aergo/v2/types" - "github.com/mr-tron/base58" "github.com/spf13/cobra" ) @@ -59,7 +59,7 @@ func execSendTX(cmd *cobra.Command, args []string) error { GasLimit: gas, }} if chainIdHash != "" { - cid, err := base58.Decode(chainIdHash) + cid, err := enc.B58Decode(chainIdHash) if err != nil { return errors.New("Wrong value in --chainidhash flag\n" + err.Error()) } diff --git a/cmd/aergocli/cmd/sendtx_test.go b/cmd/aergocli/cmd/sendtx_test.go index 5cb101dac..a4b35f872 100644 --- a/cmd/aergocli/cmd/sendtx_test.go +++ b/cmd/aergocli/cmd/sendtx_test.go @@ -4,9 +4,9 @@ import ( "testing" "github.com/aergoio/aergo/v2/cmd/aergocli/util/encoding/json" + "github.com/aergoio/aergo/v2/internal/enc" "github.com/aergoio/aergo/v2/types" "github.com/golang/mock/gomock" - "github.com/mr-tron/base58/base58" "github.com/stretchr/testify/assert" ) @@ -15,7 +15,7 @@ func TestSendTxWithMock(t *testing.T) { defer deinitMock() testTxHashString := "BdAoKcLSsrscjdpTPGe9DoFsz4mP9ezbc4Dk5fuBTT4e" - testTxHash, _ := base58.Decode(testTxHashString) + testTxHash, _ := enc.B58Decode(testTxHashString) mock.EXPECT().SendTX( gomock.Any(), // expect any value for first parameter @@ -34,7 +34,7 @@ func TestSendTxWithMock(t *testing.T) { t.Log(output) out := &types.CommitResult{} err = json.Unmarshal([]byte(output), out) - assert.Equal(t, testTxHashString, base58.Encode(out.Hash)) + assert.Equal(t, testTxHashString, enc.B58Encode(out.Hash)) } func TestSendTxFromToValidation(t *testing.T) { diff --git a/cmd/aergocli/cmd/signtx.go b/cmd/aergocli/cmd/signtx.go index d4e8b48db..a2aa1e245 100644 --- a/cmd/aergocli/cmd/signtx.go +++ b/cmd/aergocli/cmd/signtx.go @@ -8,9 +8,9 @@ import ( "github.com/aergoio/aergo/v2/account/key" crypto "github.com/aergoio/aergo/v2/account/key/crypto" "github.com/aergoio/aergo/v2/cmd/aergocli/util" + "github.com/aergoio/aergo/v2/internal/enc" "github.com/aergoio/aergo/v2/types" "github.com/btcsuite/btcd/btcec" - "github.com/mr-tron/base58/base58" "github.com/spf13/cobra" ) @@ -44,7 +44,7 @@ var signCmd = &cobra.Command{ var msg *types.Tx if privKey != "" { - rawKey, err := base58.Decode(privKey) + rawKey, err := enc.B58Decode(privKey) if err != nil { cmd.Printf("Failed: %s\n", err.Error()) return diff --git a/cmd/aergocli/cmd/signtx_test.go b/cmd/aergocli/cmd/signtx_test.go index e76a37b52..a0a0371c6 100644 --- a/cmd/aergocli/cmd/signtx_test.go +++ b/cmd/aergocli/cmd/signtx_test.go @@ -8,8 +8,8 @@ import ( "github.com/aergoio/aergo/v2/cmd/aergocli/util" "github.com/aergoio/aergo/v2/cmd/aergocli/util/encoding/json" + "github.com/aergoio/aergo/v2/internal/enc" "github.com/aergoio/aergo/v2/types" - "github.com/mr-tron/base58/base58" "github.com/stretchr/testify/assert" ) @@ -30,7 +30,7 @@ func TestSignWithKey(t *testing.T) { err = json.Unmarshal([]byte(ouputjson), &tx) assert.NoError(t, err, "should be success") - sign, err := base58.Decode(tx.Body.Sign) + sign, err := enc.B58Decode(tx.Body.Sign) assert.NoError(t, err, "should be success") assert.Equalf(t, len(sign), signLength, "wrong sign length value = %s", tx.Body.Sign) } diff --git a/cmd/aergocli/cmd/vote.go b/cmd/aergocli/cmd/vote.go index 880980b9c..31514f8a4 100644 --- a/cmd/aergocli/cmd/vote.go +++ b/cmd/aergocli/cmd/vote.go @@ -13,8 +13,8 @@ import ( "strings" "github.com/aergoio/aergo/v2/cmd/aergocli/util" + "github.com/aergoio/aergo/v2/internal/enc" "github.com/aergoio/aergo/v2/types" - "github.com/mr-tron/base58/base58" "github.com/spf13/cobra" ) @@ -84,7 +84,7 @@ func execVote(cmd *cobra.Command, args []string) { cmd.Println("too many candidates") return } - candidate, err := base58.Decode(v.(string)) + candidate, err := enc.B58Decode(v.(string)) if err != nil { cmd.Printf("Failed: %s (%s)\n", err.Error(), v) return @@ -176,7 +176,7 @@ func execBP(cmd *cobra.Command, args []string) { cmd.Println("[") comma := "," for i, r := range msg.GetVotes() { - cmd.Printf("{\"" + base58.Encode(r.Candidate) + "\":" + r.GetAmountBigInt().String() + "}") + cmd.Printf("{\"" + enc.B58Encode(r.Candidate) + "\":" + r.GetAmountBigInt().String() + "}") if i+1 == len(msg.GetVotes()) { comma = "" } diff --git a/cmd/aergocli/util/base58addr.go b/cmd/aergocli/util/base58addr.go index 90993c03a..585839ea6 100644 --- a/cmd/aergocli/util/base58addr.go +++ b/cmd/aergocli/util/base58addr.go @@ -8,9 +8,9 @@ import ( "strconv" "time" + "github.com/aergoio/aergo/v2/internal/enc" "github.com/aergoio/aergo/v2/p2p/p2putil" "github.com/aergoio/aergo/v2/types" - "github.com/mr-tron/base58/base58" ) type InOutBlockHeader struct { @@ -102,7 +102,7 @@ func FillTxBody(source *InOutTxBody, target *types.TxBody) error { target.Amount = amount.Bytes() } if source.Payload != "" { - target.Payload, err = base58.Decode(source.Payload) + target.Payload, err = enc.B58Decode(source.Payload) if err != nil { return err } @@ -116,13 +116,13 @@ func FillTxBody(source *InOutTxBody, target *types.TxBody) error { target.GasPrice = price.Bytes() } if source.ChainIdHash != "" { - target.ChainIdHash, err = base58.Decode(source.ChainIdHash) + target.ChainIdHash, err = enc.B58Decode(source.ChainIdHash) if err != nil { return err } } if source.Sign != "" { - target.Sign, err = base58.Decode(source.Sign) + target.Sign, err = enc.B58Decode(source.Sign) if err != nil { return err } @@ -146,7 +146,7 @@ func ParseBase58Tx(jsonTx []byte) ([]*types.Tx, error) { for i, in := range inputlist { tx := &types.Tx{Body: &types.TxBody{}} if in.Hash != "" { - tx.Hash, err = base58.Decode(in.Hash) + tx.Hash, err = enc.B58Decode(in.Hash) if err != nil { return nil, err } @@ -183,7 +183,7 @@ func ConvTxEx(tx *types.Tx, payloadType EncodingType) *InOutTx { if tx == nil { return out } - out.Hash = base58.Encode(tx.Hash) + out.Hash = enc.B58Encode(tx.Hash) out.Body.Nonce = tx.Body.Nonce if tx.Body.Account != nil { out.Body.Account = types.EncodeAddress(tx.Body.Account) @@ -198,21 +198,21 @@ func ConvTxEx(tx *types.Tx, payloadType EncodingType) *InOutTx { case Raw: out.Body.Payload = string(tx.Body.Payload) case Base58: - out.Body.Payload = base58.Encode(tx.Body.Payload) + out.Body.Payload = enc.B58Encode(tx.Body.Payload) } out.Body.GasLimit = tx.Body.GasLimit if tx.Body.GasPrice != nil { out.Body.GasPrice = new(big.Int).SetBytes(tx.Body.GasPrice).String() } - out.Body.ChainIdHash = base58.Encode(tx.Body.ChainIdHash) - out.Body.Sign = base58.Encode(tx.Body.Sign) + out.Body.ChainIdHash = enc.B58Encode(tx.Body.ChainIdHash) + out.Body.Sign = enc.B58Encode(tx.Body.Sign) out.Body.Type = tx.Body.Type return out } func ConvTxInBlockEx(txInBlock *types.TxInBlock, payloadType EncodingType) *InOutTxInBlock { out := &InOutTxInBlock{TxIdx: &InOutTxIdx{}, Tx: &InOutTx{}} - out.TxIdx.BlockHash = base58.Encode(txInBlock.GetTxIdx().GetBlockHash()) + out.TxIdx.BlockHash = enc.B58Encode(txInBlock.GetTxIdx().GetBlockHash()) out.TxIdx.Idx = txInBlock.GetTxIdx().GetIdx() out.Tx = ConvTxEx(txInBlock.GetTx(), payloadType) return out @@ -221,18 +221,18 @@ func ConvTxInBlockEx(txInBlock *types.TxInBlock, payloadType EncodingType) *InOu func ConvBlock(b *types.Block) *InOutBlock { out := &InOutBlock{} if b != nil { - out.Hash = base58.Encode(b.Hash) - out.Header.ChainID = base58.Encode(b.GetHeader().GetChainID()) + out.Hash = enc.B58Encode(b.Hash) + out.Header.ChainID = enc.B58Encode(b.GetHeader().GetChainID()) out.Header.Version = types.DecodeChainIdVersion(b.GetHeader().GetChainID()) - out.Header.PrevBlockHash = base58.Encode(b.GetHeader().GetPrevBlockHash()) + out.Header.PrevBlockHash = enc.B58Encode(b.GetHeader().GetPrevBlockHash()) out.Header.BlockNo = b.GetHeader().GetBlockNo() out.Header.Timestamp = b.GetHeader().GetTimestamp() - out.Header.BlockRootHash = base58.Encode(b.GetHeader().GetBlocksRootHash()) - out.Header.TxRootHash = base58.Encode(b.GetHeader().GetTxsRootHash()) - out.Header.ReceiptsRootHash = base58.Encode(b.GetHeader().GetReceiptsRootHash()) + out.Header.BlockRootHash = enc.B58Encode(b.GetHeader().GetBlocksRootHash()) + out.Header.TxRootHash = enc.B58Encode(b.GetHeader().GetTxsRootHash()) + out.Header.ReceiptsRootHash = enc.B58Encode(b.GetHeader().GetReceiptsRootHash()) out.Header.Confirms = b.GetHeader().GetConfirms() - out.Header.PubKey = base58.Encode(b.GetHeader().GetPubKey()) - out.Header.Sign = base58.Encode(b.GetHeader().GetSign()) + out.Header.PubKey = enc.B58Encode(b.GetHeader().GetPubKey()) + out.Header.Sign = enc.B58Encode(b.GetHeader().GetSign()) if b.GetHeader().GetCoinbaseAccount() != nil { out.Header.CoinbaseAccount = types.EncodeAddress(b.GetHeader().GetCoinbaseAccount()) } @@ -254,10 +254,10 @@ func ConvPeer(p *types.Peer) *InOutPeer { out.Role = p.AcceptedRole.String() out.Address.Address = p.GetAddress().GetAddress() out.Address.Port = strconv.Itoa(int(p.GetAddress().GetPort())) - out.Address.PeerId = base58.Encode(p.GetAddress().GetPeerID()) + out.Address.PeerId = enc.B58Encode(p.GetAddress().GetPeerID()) out.LastCheck = time.Unix(0, p.GetLashCheck()) out.BestBlock.BlockNo = p.GetBestblock().GetBlockNo() - out.BestBlock.BlockHash = base58.Encode(p.GetBestblock().GetBlockHash()) + out.BestBlock.BlockHash = enc.B58Encode(p.GetBestblock().GetBlockHash()) out.State = types.PeerState(p.State).String() out.Hidden = p.Hidden out.Self = p.Selfpeer @@ -273,7 +273,7 @@ func ConvPeerLong(p *types.Peer) *LongInOutPeer { out := &LongInOutPeer{InOutPeer: *ConvPeer(p)} out.ProducerIDs = make([]string, len(p.Address.ProducerIDs)) for i, pid := range p.Address.ProducerIDs { - out.ProducerIDs[i] = base58.Encode(pid) + out.ProducerIDs[i] = enc.B58Encode(pid) } if p.Address.Role == types.PeerRole_Agent { out.Certificates = make([]*InOutCert, len(p.Certificates)) @@ -283,7 +283,7 @@ func ConvPeerLong(p *types.Peer) *LongInOutPeer { addrs = append(addrs, string(ad)) } out.Certificates[i] = &InOutCert{CertVersion: cert.CertVersion, - ProducerID: base58.Encode(cert.BPID), AgentID: base58.Encode(cert.AgentID), + ProducerID: enc.B58Encode(cert.BPID), AgentID: enc.B58Encode(cert.AgentID), CreateTime: time.Unix(0, cert.CreateTime), ExpireTime: time.Unix(0, cert.ExpireTime), Addresses: addrs} } @@ -296,10 +296,10 @@ func ConvBlockchainStatus(in *types.BlockchainStatus) string { if in == nil { return "" } - out.Hash = base58.Encode(in.BestBlockHash) + out.Hash = enc.B58Encode(in.BestBlockHash) out.Height = in.BestHeight - out.ChainIdHash = base58.Encode(in.BestChainIdHash) + out.ChainIdHash = enc.B58Encode(in.BestChainIdHash) toJRM := func(s string) *json.RawMessage { if len(s) > 0 { diff --git a/cmd/aergocli/util/base58addr_test.go b/cmd/aergocli/util/base58addr_test.go index a3f962b98..34f37c972 100644 --- a/cmd/aergocli/util/base58addr_test.go +++ b/cmd/aergocli/util/base58addr_test.go @@ -3,8 +3,8 @@ package util import ( "testing" + "github.com/aergoio/aergo/v2/internal/enc" "github.com/aergoio/aergo/v2/types" - "github.com/mr-tron/base58/base58" "github.com/stretchr/testify/assert" ) @@ -13,8 +13,8 @@ func TestParseConvBase58Tx(t *testing.T) { res, err := ParseBase58Tx([]byte(testjson)) assert.NoError(t, err, "should be success") assert.NotEmpty(t, res, "failed to parse json") - assert.Equal(t, "525mQMtsWaDLVJbzQZgTFkSG33gtZsho7m4io1HUCeJi", base58.Encode(res[0].Hash), "wrong hash") - assert.Equal(t, "3tMHYrizQ532D1WJkt5RSs5AcRmq7betw8zvC66Wh3XHUdvNpNzLWh1SkkGYMGJ669nCVuYHrhwfg1HrUUp6KDwzK", base58.Encode(res[0].Body.Sign), "wrong sign") + assert.Equal(t, "525mQMtsWaDLVJbzQZgTFkSG33gtZsho7m4io1HUCeJi", enc.B58Encode(res[0].Hash), "wrong hash") + assert.Equal(t, "3tMHYrizQ532D1WJkt5RSs5AcRmq7betw8zvC66Wh3XHUdvNpNzLWh1SkkGYMGJ669nCVuYHrhwfg1HrUUp6KDwzK", enc.B58Encode(res[0].Body.Sign), "wrong sign") account, err := types.DecodeAddress("AsiFCzSukVNUGufJSzSNLA1nKx39NxKcVBEWvW3riyfixcBjN1Qd") assert.NoError(t, err, "should be success") @@ -31,8 +31,8 @@ func TestParseBase58TxBody(t *testing.T) { assert.NoError(t, err, "should be success") assert.NotEmpty(t, res, "failed to parse json") - assert.Equal(t, "3roWPzztf5aLLh16vAnd2ugcPux3wJ1oqqvqkWARobjuAC32xftF42nnbTkXUQdkDaFvuUmctrpQSv8FAVUKcywHW", base58.Encode(res.Sign), "wrong sign") - assert.Equal(t, "aergo", base58.Encode(res.Payload), "wrong payload") + assert.Equal(t, "3roWPzztf5aLLh16vAnd2ugcPux3wJ1oqqvqkWARobjuAC32xftF42nnbTkXUQdkDaFvuUmctrpQSv8FAVUKcywHW", enc.B58Encode(res.Sign), "wrong sign") + assert.Equal(t, "aergo", enc.B58Encode(res.Payload), "wrong payload") account, err := types.DecodeAddress("AsiFCzSukVNUGufJSzSNLA1nKx39NxKcVBEWvW3riyfixcBjN1Qd") assert.NoError(t, err, "should be success") assert.Equal(t, account, res.Account, "wrong account") @@ -68,7 +68,7 @@ func TestBlockConvBase58(t *testing.T) { recipient, err := types.DecodeAddress(recipientBase58) assert.NoError(t, err, "should be decode recipient") - payload, err := base58.Decode(payloadBase58) + payload, err := enc.B58Decode(payloadBase58) assert.NoError(t, err, "should be decode payload") testTx := &types.Tx{Body: &types.TxBody{ diff --git a/cmd/aergocli/util/encoding/json/decode.go b/cmd/aergocli/util/encoding/json/decode.go index 9fd2838d3..ead4c7157 100644 --- a/cmd/aergocli/util/encoding/json/decode.go +++ b/cmd/aergocli/util/encoding/json/decode.go @@ -17,7 +17,7 @@ import ( "unicode/utf16" "unicode/utf8" - "github.com/mr-tron/base58/base58" + "github.com/aergoio/aergo/v2/internal/enc" ) // Unmarshal parses the JSON-encoded data and stores the result @@ -934,7 +934,7 @@ func (d *decodeState) literalStore(item []byte, v reflect.Value, fromQuoted bool d.saveError(&UnmarshalTypeError{Value: "string", Type: v.Type(), Offset: int64(d.readIndex())}) break } - b, err := base58.Decode(string(s)) + b, err := enc.B58Decode(string(s)) if err != nil { d.saveError(err) break diff --git a/cmd/aergocli/util/encoding/json/encode.go b/cmd/aergocli/util/encoding/json/encode.go index 337129a21..b5d825124 100644 --- a/cmd/aergocli/util/encoding/json/encode.go +++ b/cmd/aergocli/util/encoding/json/encode.go @@ -23,7 +23,7 @@ import ( "unicode" "unicode/utf8" - "github.com/mr-tron/base58/base58" + "github.com/aergoio/aergo/v2/internal/enc" ) // Marshal returns the JSON encoding of v. @@ -724,7 +724,7 @@ func encodeByteSlice(e *encodeState, v reflect.Value, _ encOpts) { } s := v.Bytes() e.WriteByte('"') - e.WriteString(base58.Encode(s)) + e.WriteString(enc.B58Encode(s)) e.WriteByte('"') } diff --git a/cmd/aergoluac/encoding/codeEncoding.go b/cmd/aergoluac/encoding/codeEncoding.go index a2e850158..d0a383b01 100644 --- a/cmd/aergoluac/encoding/codeEncoding.go +++ b/cmd/aergoluac/encoding/codeEncoding.go @@ -5,18 +5,18 @@ import ( "errors" "fmt" - "github.com/anaskhan96/base58check" + "github.com/aergoio/aergo/v2/internal/enc" ) const CodeVersion = 0xC0 func EncodeCode(code []byte) string { - encoded, _ := base58check.Encode(fmt.Sprintf("%x", CodeVersion), hex.EncodeToString(code)) + encoded, _ := enc.B58CheckEncode(fmt.Sprintf("%x", CodeVersion), hex.EncodeToString(code)) return encoded } func DecodeCode(encodedCode string) ([]byte, error) { - decodedString, err := base58check.Decode(encodedCode) + decodedString, err := enc.B58CheckDecode(encodedCode) if err != nil { return nil, err } diff --git a/cmd/aergosvr/init.go b/cmd/aergosvr/init.go index b88a9c0a4..b1396eaae 100644 --- a/cmd/aergosvr/init.go +++ b/cmd/aergosvr/init.go @@ -36,7 +36,7 @@ var initGenesis = &cobra.Command{ if core != nil { exist := core.GetGenesisInfo() if exist != nil { - fmt.Printf("genesis block(%s) is already initialized\n", enc.ToString(exist.Block().GetHash())) + fmt.Printf("genesis block(%s) is already initialized\n", enc.B58Encode(exist.Block().GetHash())) core.Close() return } @@ -71,7 +71,7 @@ var initGenesis = &cobra.Command{ } g := core.GetGenesisInfo() - fmt.Printf("genesis block[%s] is created in (%s)\n", enc.ToString(g.Block().GetHash()), cfg.DataDir) + fmt.Printf("genesis block[%s] is created in (%s)\n", enc.B58Encode(g.Block().GetHash()), cfg.DataDir) } }, } diff --git a/cmd/colaris/cmd/current.go b/cmd/colaris/cmd/current.go index 4d971f197..a53bd07d2 100644 --- a/cmd/colaris/cmd/current.go +++ b/cmd/colaris/cmd/current.go @@ -10,8 +10,7 @@ import ( "time" "github.com/aergoio/aergo/v2/cmd/aergocli/util" - - "github.com/mr-tron/base58/base58" + "github.com/aergoio/aergo/v2/internal/enc" "github.com/aergoio/aergo/v2/types" "github.com/spf13/cobra" @@ -38,7 +37,7 @@ func execCurrentPeers(cmd *cobra.Command, args []string) { var err error if cmd.Flags().Changed("ref") == true { - blockHash, err = base58.Decode(cpKey) + blockHash, err = enc.B58Decode(cpKey) if err != nil { cmd.Printf("Failed: %s", err.Error()) return diff --git a/consensus/chain/block.go b/consensus/chain/block.go index d81aa4649..9067bf501 100644 --- a/consensus/chain/block.go +++ b/consensus/chain/block.go @@ -124,7 +124,7 @@ func (g *BlockGenerator) Rejected() *RejTxInfo { // SetTimeoutTx set bState.timeoutTx to tx. func (g *BlockGenerator) SetTimeoutTx(tx types.Transaction) { - logger.Warn().Str("hash", enc.ToString(tx.GetHash())).Msg("timeout tx marked for eviction") + logger.Warn().Str("hash", enc.B58Encode(tx.GetHash())).Msg("timeout tx marked for eviction") g.bState.SetTimeoutTx(tx) } @@ -211,7 +211,7 @@ func ConnectBlock(hs component.ICompSyncRequester, block *types.Block, blockStat func SyncChain(hs *component.ComponentHub, targetHash []byte, targetNo types.BlockNo, peerID types.PeerID) error { logger.Info().Stringer("peer", types.LogPeerShort(peerID)).Uint64("no", targetNo). - Str("hash", enc.ToString(targetHash)).Msg("request to sync for consensus") + Str("hash", enc.B58Encode(targetHash)).Msg("request to sync for consensus") notiC := make(chan error) hs.Tell(message.SyncerSvc, &message.SyncStart{PeerID: peerID, TargetNo: targetNo, NotifyC: notiC}) @@ -221,7 +221,7 @@ func SyncChain(hs *component.ComponentHub, targetHash []byte, targetNo types.Blo case err := <-notiC: if err != nil { logger.Error().Err(err).Uint64("no", targetNo). - Str("hash", enc.ToString(targetHash)). + Str("hash", enc.B58Encode(targetHash)). Msg("failed to sync") return err diff --git a/consensus/impl/dpos/blockfactory.go b/consensus/impl/dpos/blockfactory.go index f8ee9ca7b..126497848 100644 --- a/consensus/impl/dpos/blockfactory.go +++ b/consensus/impl/dpos/blockfactory.go @@ -264,7 +264,7 @@ func (bf *BlockFactory) generateBlock(execCtx context.Context, bpi *bpInfo, lpbN logger.Info(). Str("BP", bf.ID).Str("id", block.ID()). - Str("sroot", enc.ToString(block.GetHeader().GetBlocksRootHash())). + Str("sroot", enc.B58Encode(block.GetHeader().GetBlocksRootHash())). Uint64("no", block.BlockNo()).Uint64("confirms", block.Confirms()). Uint64("lpb", lpbNo). Msg("block produced") @@ -277,7 +277,7 @@ func (bf *BlockFactory) rejected() *chain.RejTxInfo { } func (bf *BlockFactory) setRejected(rej *chain.RejTxInfo) { - logger.Warn().Str("hash", enc.ToString(rej.Hash())).Msg("timeout tx reserved for rescheduling") + logger.Warn().Str("hash", enc.B58Encode(rej.Hash())).Msg("timeout tx reserved for rescheduling") bf.recentRejectedTx = rej } diff --git a/consensus/impl/dpos/lib_test.go b/consensus/impl/dpos/lib_test.go index 0128398f8..9628f2a06 100644 --- a/consensus/impl/dpos/lib_test.go +++ b/consensus/impl/dpos/lib_test.go @@ -50,7 +50,7 @@ func newTestChain(clusterSize uint16) (*testChain, error) { tc := &testChain{ chain: make([]*types.Block, 0), status: NewStatus(&testCluster{size: clusterSize}, nil, nil, 0), - bpid: enc.ToString(b), + bpid: enc.B58Encode(b), lpb: make(map[string]types.BlockNo), bpKey: bpKey, bpClusterSize: clusterSize, @@ -78,7 +78,7 @@ func (tc *testChain) addBlock(i types.BlockNo) error { if err != nil { return err } - spk := enc.ToString(b) + spk := enc.B58Encode(b) prevBlock := tc.chain[len(tc.chain)-1] block := newBlockFromPrev(prevBlock, 0, types.DummyBlockVersionner(0)) diff --git a/consensus/impl/raftv2/blockfactory.go b/consensus/impl/raftv2/blockfactory.go index 55b0baf67..661cb48ac 100644 --- a/consensus/impl/raftv2/blockfactory.go +++ b/consensus/impl/raftv2/blockfactory.go @@ -541,7 +541,7 @@ func (bf *BlockFactory) generateBlock(work *Work) (*types.Block, *state.BlockSta } logger.Info().Str("blockProducer", bf.ID).Str("raftID", EtcdIDToString(bf.bpc.NodeID())). - Str("sroot", enc.ToString(block.GetHeader().GetBlocksRootHash())). + Str("sroot", enc.B58Encode(block.GetHeader().GetBlocksRootHash())). Uint64("no", block.GetHeader().GetBlockNo()). Str("hash", block.ID()). Msg("block produced") diff --git a/consensus/impl/raftv2/cluster.go b/consensus/impl/raftv2/cluster.go index 2cf27b7cb..18ea2284e 100644 --- a/consensus/impl/raftv2/cluster.go +++ b/consensus/impl/raftv2/cluster.go @@ -409,7 +409,7 @@ func (cl *Cluster) isValidMember(member *consensus.Member) error { } // check if peerID of this node is valid - if cl.NodeName() == member.Name && enc.ToString([]byte(member.GetPeerID())) != cl.NodePeerID() { + if cl.NodeName() == member.Name && enc.B58Encode([]byte(member.GetPeerID())) != cl.NodePeerID() { logger.Error().Str("config", member.GetPeerID().String()).Str("cluster peerid", cl.NodePeerID()).Msg("peerID value is not matched with P2P") return ErrInvalidRaftPeerID } @@ -433,7 +433,7 @@ func (cl *Cluster) addMember(member *consensus.Member, applied bool) error { // notify to p2p TODO temporary code peerID, err := types.IDFromBytes(member.PeerID) if err != nil { - logger.Panic().Err(err).Str("peerid", enc.ToString(member.PeerID)).Msg("invalid member peerid") + logger.Panic().Err(err).Str("peerid", enc.B58Encode(member.PeerID)).Msg("invalid member peerid") } if cl.notifyFn != nil { @@ -466,7 +466,7 @@ func (cl *Cluster) removeMember(member *consensus.Member) error { // notify to p2p TODO temporary code peerID, err := types.IDFromBytes(member.PeerID) if err != nil { - logger.Panic().Err(err).Str("peerid", enc.ToString(member.PeerID)).Msg("invalid member peerid") + logger.Panic().Err(err).Str("peerid", enc.B58Encode(member.PeerID)).Msg("invalid member peerid") } if cl.notifyFn != nil { @@ -494,7 +494,7 @@ func (cl *Cluster) ValidateAndMergeExistingCluster(existingCl *Cluster) bool { } // TODO check my network config is equal to member of remote - if enc.ToString(remoteMember.PeerID) != cl.NodePeerID() { + if enc.B58Encode(remoteMember.PeerID) != cl.NodePeerID() { logger.Error().Msg("peerid is different with peerid of member of existing cluster") } diff --git a/consensus/impl/sbp/sbp.go b/consensus/impl/sbp/sbp.go index a8ef44cc0..1d4bf92d5 100644 --- a/consensus/impl/sbp/sbp.go +++ b/consensus/impl/sbp/sbp.go @@ -202,7 +202,7 @@ func (s *SimpleBlockFactory) Start() { continue } logger.Info().Uint64("no", block.GetHeader().GetBlockNo()).Str("hash", block.ID()). - Str("TrieRoot", enc.ToString(block.GetHeader().GetBlocksRootHash())). + Str("TrieRoot", enc.B58Encode(block.GetHeader().GetBlocksRootHash())). Err(err).Msg("block produced") chain.ConnectBlock(s, block, blockState, time.Second) diff --git a/consensus/raftCommon.go b/consensus/raftCommon.go index 4bcbd42f4..c4b96d63e 100644 --- a/consensus/raftCommon.go +++ b/consensus/raftCommon.go @@ -5,12 +5,12 @@ import ( "context" "crypto/sha1" "encoding/binary" - "encoding/gob" "encoding/json" "errors" "fmt" "io" + "github.com/aergoio/aergo/v2/internal/common" "github.com/aergoio/aergo/v2/internal/enc" "github.com/aergoio/aergo/v2/types" "github.com/aergoio/etcd/raft" @@ -59,13 +59,7 @@ type WalEntry struct { } func (we *WalEntry) ToBytes() ([]byte, error) { - var val bytes.Buffer - encoder := gob.NewEncoder(&val) - if err := encoder.Encode(we); err != nil { - logger.Panic().Err(err).Msg("raft entry to bytes error") - } - - return val.Bytes(), nil + return common.GobEncode(we) } func (we *WalEntry) ToString() string { @@ -203,7 +197,7 @@ func (csnap *ChainSnapshot) ToString() string { if csnap == nil || csnap.Hash == nil { return "csnap: empty" } - return fmt.Sprintf("chainsnap:(no=%d, hash=%s)", csnap.No, enc.ToString(csnap.Hash)) + return fmt.Sprintf("chainsnap:(no=%d, hash=%s)", csnap.No, enc.B58Encode(csnap.Hash)) } /* diff --git a/contract/enterprise/validate.go b/contract/enterprise/validate.go index 1e95a42f3..0d8b3ba05 100644 --- a/contract/enterprise/validate.go +++ b/contract/enterprise/validate.go @@ -2,13 +2,13 @@ package enterprise import ( "bytes" - "encoding/base64" "encoding/json" "errors" "fmt" "strings" "github.com/aergoio/aergo/v2/consensus" + "github.com/aergoio/aergo/v2/internal/enc" "github.com/aergoio/aergo/v2/state" "github.com/aergoio/aergo/v2/types" ) @@ -265,7 +265,7 @@ func checkRPCPermissions(v string) error { return fmt.Errorf("invalid RPC permission %s", v) } - if _, err := base64.StdEncoding.DecodeString(values[0]); err != nil { + if _, err := enc.B64Decode(values[0]); err != nil { return fmt.Errorf("invalid RPC cert %s", v) } diff --git a/contract/statesql.go b/contract/statesql.go index d5fd02547..4f4fe69cf 100644 --- a/contract/statesql.go +++ b/contract/statesql.go @@ -49,7 +49,7 @@ func init() { sql.Register(statesqlDriver, &SQLiteDriver{ ConnectHook: func(conn *SQLiteConn) error { if _, ok := database.DBs[database.OpenDbName]; !ok { - b, err := enc.ToBytes(database.OpenDbName) + b, err := enc.B58Decode(database.OpenDbName) if err != nil { sqlLgr.Error().Err(err).Msg("Open SQL Connection") return nil diff --git a/contract/system/execute.go b/contract/system/execute.go index b971c414a..5975988ab 100644 --- a/contract/system/execute.go +++ b/contract/system/execute.go @@ -10,9 +10,9 @@ import ( "fmt" "math/big" + "github.com/aergoio/aergo/v2/internal/enc" "github.com/aergoio/aergo/v2/state" "github.com/aergoio/aergo/v2/types" - "github.com/mr-tron/base58" ) // SystemContext is context of executing aergo.system transaction and filled after validation. @@ -115,7 +115,7 @@ func GetVotes(scs *state.ContractState, address []byte) ([]*types.VoteInfo, erro if bytes.Equal(key, defaultVoteKey) { for offset := 0; offset < len(v.Candidate); offset += PeerIDLength { - candi := base58.Encode(v.Candidate[offset : offset+PeerIDLength]) + candi := enc.B58Encode(v.Candidate[offset : offset+PeerIDLength]) result.Candidates = append(result.Candidates, candi) } } else { diff --git a/contract/system/execute_test.go b/contract/system/execute_test.go index 6f1f8acff..4bf2d5a42 100644 --- a/contract/system/execute_test.go +++ b/contract/system/execute_test.go @@ -9,8 +9,8 @@ import ( "testing" "github.com/aergoio/aergo/v2/config" + "github.com/aergoio/aergo/v2/internal/enc" "github.com/aergoio/aergo/v2/types" - "github.com/mr-tron/base58/base58" "github.com/stretchr/testify/assert" ) @@ -310,7 +310,7 @@ func TestValidateSystemTxForVoting(t *testing.T) { defer deinitTest() const testSender = "AmPNYHyzyh9zweLwDyuoiUuTVCdrdksxkRWDjVJS76WQLExa2Jr4" const testCandidate = "16Uiu2HAmUJhjwotQqm7eGyZh1ZHrVviQJrdm2roQouD329vxZEkx" - candidates, err := base58.Decode(testCandidate) + candidates, err := enc.B58Decode(testCandidate) assert.NoError(t, err, "could not decode candidates") account, err := types.DecodeAddress(testSender) diff --git a/contract/system/vote.go b/contract/system/vote.go index cf5f9e083..63163a54b 100644 --- a/contract/system/vote.go +++ b/contract/system/vote.go @@ -16,7 +16,6 @@ import ( "github.com/aergoio/aergo/v2/state" "github.com/aergoio/aergo/v2/types" "github.com/aergoio/aergo/v2/types/dbkey" - "github.com/mr-tron/base58" ) const ( @@ -145,7 +144,7 @@ func newVoteCmd(ctx *SystemContext) (sysCmd, error) { return nil, err } for _, v := range ctx.Call.Args { - candidate, _ := base58.Decode(v.(string)) + candidate, _ := enc.B58Decode(v.(string)) cmd.candidate = append(cmd.candidate, candidate...) } } @@ -323,7 +322,7 @@ func BuildOrderedCandidates(vote map[string]*big.Int) []string { l := voteResult.buildVoteList() bps := make([]string, 0, len(l.Votes)) for _, v := range l.Votes { - bp := enc.ToString(v.Candidate) + bp := enc.B58Encode(v.Candidate) bps = append(bps, bp) } return bps @@ -357,7 +356,7 @@ func GetRankers(ar AccountStateReader) ([]string, error) { bps := make([]string, 0, n) for _, v := range vl.Votes { - bps = append(bps, enc.ToString(v.Candidate)) + bps = append(bps, enc.B58Encode(v.Candidate)) } return bps, nil } diff --git a/contract/system/vote_test.go b/contract/system/vote_test.go index 8eff82f3b..ef8cad4b5 100644 --- a/contract/system/vote_test.go +++ b/contract/system/vote_test.go @@ -14,10 +14,10 @@ import ( "testing" "github.com/aergoio/aergo-lib/db" + "github.com/aergoio/aergo/v2/internal/enc" "github.com/aergoio/aergo/v2/state" "github.com/aergoio/aergo/v2/types" "github.com/libp2p/go-libp2p-core/crypto" - "github.com/mr-tron/base58" "github.com/stretchr/testify/assert" ) @@ -82,7 +82,7 @@ func TestVoteResult(t *testing.T) { testResult := map[string]*big.Int{} for i := 0; i < testSize; i++ { to := fmt.Sprintf("%39d", i) //39:peer id length - testResult[base58.Encode([]byte(to))] = new(big.Int).SetUint64(uint64(i * i)) + testResult[enc.B58Encode([]byte(to))] = new(big.Int).SetUint64(uint64(i * i)) } err = InitVoteResult(scs, nil) assert.NotNil(t, err, "argument should not be nil") @@ -166,7 +166,7 @@ func TestBasicStakingVotingUnstaking(t *testing.T) { result, err := getVoteResult(scs, defaultVoteKey, 23) assert.NoError(t, err, "voting failed") assert.EqualValues(t, len(result.GetVotes()), 1, "invalid voting result") - assert.Equal(t, voting.arg(0), base58.Encode(result.GetVotes()[0].Candidate), "invalid candidate in voting result") + assert.Equal(t, voting.arg(0), enc.B58Encode(result.GetVotes()[0].Candidate), "invalid candidate in voting result") assert.Equal(t, types.StakingMinimum.Bytes(), result.GetVotes()[0].Amount, "invalid amount in voting result") tx.Body.Payload = buildStakingPayload(false) @@ -224,7 +224,7 @@ func buildVotingPayload(count int) []byte { for i := 0; i < count; i++ { peerID := make([]byte, PeerIDLength) peerID[0] = byte(i) - ci.Args = append(ci.Args, base58.Encode(peerID)) + ci.Args = append(ci.Args, enc.B58Encode(peerID)) } payload, _ := json.Marshal(ci) return payload diff --git a/contract/system/voteresult.go b/contract/system/voteresult.go index b183f5fa3..f9247be7c 100644 --- a/contract/system/voteresult.go +++ b/contract/system/voteresult.go @@ -12,7 +12,6 @@ import ( "github.com/aergoio/aergo/v2/state" "github.com/aergoio/aergo/v2/types" "github.com/aergoio/aergo/v2/types/dbkey" - "github.com/mr-tron/base58" ) type VoteResult struct { @@ -57,7 +56,7 @@ func (voteResult *VoteResult) SubVote(vote *types.Vote) error { } else { for offset := 0; offset < len(vote.Candidate); offset += PeerIDLength { peer := vote.Candidate[offset : offset+PeerIDLength] - pkey := base58.Encode(peer) + pkey := enc.B58Encode(peer) voteResult.rmap[pkey] = new(big.Int).Sub(voteResult.rmap[pkey], vote.GetAmountBigInt()) } } @@ -81,10 +80,10 @@ func (voteResult *VoteResult) AddVote(vote *types.Vote) error { } else { for offset := 0; offset < len(vote.Candidate); offset += PeerIDLength { key := vote.Candidate[offset : offset+PeerIDLength] - if voteResult.rmap[base58.Encode(key)] == nil { - voteResult.rmap[base58.Encode(key)] = new(big.Int).SetUint64(0) + if voteResult.rmap[enc.B58Encode(key)] == nil { + voteResult.rmap[enc.B58Encode(key)] = new(big.Int).SetUint64(0) } - voteResult.rmap[base58.Encode(key)] = new(big.Int).Add(voteResult.rmap[base58.Encode(key)], vote.GetAmountBigInt()) + voteResult.rmap[enc.B58Encode(key)] = new(big.Int).Add(voteResult.rmap[enc.B58Encode(key)], vote.GetAmountBigInt()) } } return nil @@ -99,7 +98,7 @@ func (vr *VoteResult) buildVoteList() *types.VoteList { if vr.ex { vote.Candidate = []byte(k) } else { - vote.Candidate, _ = enc.ToBytes(k) + vote.Candidate, _ = enc.B58Decode(k) } voteList.Votes = append(voteList.Votes, vote) } @@ -160,7 +159,7 @@ func loadVoteResult(scs *state.ContractState, key []byte) (*VoteResult, error) { if voteResult.ex { voteResult.rmap[string(v.Candidate)] = v.GetAmountBigInt() } else { - voteResult.rmap[base58.Encode(v.Candidate)] = v.GetAmountBigInt() + voteResult.rmap[enc.B58Encode(v.Candidate)] = v.GetAmountBigInt() } } } diff --git a/contract/system/vprt.go b/contract/system/vprt.go index 09009c9ab..aa6d645bc 100644 --- a/contract/system/vprt.go +++ b/contract/system/vprt.go @@ -611,7 +611,7 @@ func (v *vpr) add(id types.AccountID, addr []byte, power *big.Int) { if vprLogger.IsDebugEnabled() { vprLogger.Debug(). Str("op", "add"). - Str("addr", enc.ToString(addr)). + Str("addr", enc.B58Encode(addr)). Str("orig", lhs.String()). Str("delta", power.String()). Msg("prepare voting power change") @@ -631,7 +631,7 @@ func (v *vpr) sub(id types.AccountID, addr []byte, power *big.Int) { if vprLogger.IsDebugEnabled() { vprLogger.Debug(). Str("op", "sub"). - Str("addr", enc.ToString(addr)). + Str("addr", enc.B58Encode(addr)). Str("orig", lhs.String()). Str("delta", power.String()). Msg("prepare voting power change") @@ -710,7 +710,7 @@ func (v *vpr) pickVotingRewardWinner(seed int64) (types.Address, error) { if vprLogger.IsDebugEnabled() { vprLogger.Debug(). Str("total voting power", totalVp.String()). - Str("addr", enc.ToString(winner)). + Str("addr", enc.B58Encode(winner)). Msg("pick voting reward winner") } diff --git a/contract/system/vprt_test.go b/contract/system/vprt_test.go index 2cd9582b3..80652c2f0 100644 --- a/contract/system/vprt_test.go +++ b/contract/system/vprt_test.go @@ -176,8 +176,8 @@ func openSystemAccount(t *testing.T) *state.ContractState { assert.NoError(t, err, "fail to open the system contract state") logger.Debug().Msgf( "(after) state, contract: %s, %s\n", - enc.ToString(vprStateDB.GetRoot()), - enc.ToString(s.GetStorageRoot())) + enc.B58Encode(vprStateDB.GetRoot()), + enc.B58Encode(s.GetStorageRoot())) return s } diff --git a/contract/vm.go b/contract/vm.go index 9bd1442c8..3f44d2b7d 100644 --- a/contract/vm.go +++ b/contract/vm.go @@ -174,7 +174,7 @@ func newContractInfo(cs *callState, sender, contractId []byte, rp uint64, amount func getTraceFile(blkno uint64, tx []byte) *os.File { f, _ := os.OpenFile(fmt.Sprintf("%s%s%d.trace", os.TempDir(), string(os.PathSeparator), blkno), os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0644) if f != nil { - _, _ = f.WriteString(fmt.Sprintf("[START TX]: %s\n", enc.ToString(tx))) + _, _ = f.WriteString(fmt.Sprintf("[START TX]: %s\n", enc.B58Encode(tx))) } return f } @@ -914,8 +914,8 @@ func setRandomSeed(ctx *vmContext) { if ctx.isQuery { randSrc = rand.NewSource(ctx.blockInfo.Ts) } else { - b, _ := new(big.Int).SetString(enc.ToString(ctx.blockInfo.PrevBlockHash[:7]), 62) - t, _ := new(big.Int).SetString(enc.ToString(ctx.txHash[:7]), 62) + b, _ := new(big.Int).SetString(enc.B58Encode(ctx.blockInfo.PrevBlockHash[:7]), 62) + t, _ := new(big.Int).SetString(enc.B58Encode(ctx.txHash[:7]), 62) b.Add(b, t) randSrc = rand.NewSource(b.Int64()) } diff --git a/contract/vm_callback.go b/contract/vm_callback.go index 5cf046388..55f65f43b 100644 --- a/contract/vm_callback.go +++ b/contract/vm_callback.go @@ -785,7 +785,7 @@ func luaGetSender(L *LState, service C.int) *C.char { //export luaGetHash func luaGetHash(L *LState, service C.int) *C.char { ctx := contexts[service] - return C.CString(enc.ToString(ctx.txHash)) + return C.CString(enc.B58Encode(ctx.txHash)) } //export luaGetBlockNo @@ -823,7 +823,7 @@ func luaGetOrigin(L *LState, service C.int) *C.char { //export luaGetPrevBlockHash func luaGetPrevBlockHash(L *LState, service C.int) *C.char { ctx := contexts[service] - return C.CString(enc.ToString(ctx.blockInfo.PrevBlockHash)) + return C.CString(enc.B58Encode(ctx.blockInfo.PrevBlockHash)) } //export luaGetDbHandle diff --git a/contract/vm_direct/vm_direct.go b/contract/vm_direct/vm_direct.go index 574bf8bde..d66c24c5a 100644 --- a/contract/vm_direct/vm_direct.go +++ b/contract/vm_direct/vm_direct.go @@ -1,19 +1,19 @@ package vm_direct import ( - "errors" - "math/big" "bytes" - "encoding/json" "context" - "os" + "encoding/json" + "errors" "fmt" + "math/big" + "os" "time" "github.com/aergoio/aergo-lib/db" "github.com/aergoio/aergo-lib/log" - "github.com/aergoio/aergo/v2/consensus" "github.com/aergoio/aergo/v2/config" + "github.com/aergoio/aergo/v2/consensus" "github.com/aergoio/aergo/v2/contract" "github.com/aergoio/aergo/v2/contract/name" "github.com/aergoio/aergo/v2/contract/system" @@ -26,9 +26,9 @@ import ( type ChainType int const ( - ChainTypeMainNet ChainType = iota - ChainTypeTestNet - ChainTypeUnitTest + ChainTypeMainNet ChainType = iota + ChainTypeTestNet + ChainTypeUnitTest ) const ( @@ -191,14 +191,13 @@ func (bc *DummyChain) SetCoinbaseAccount(address []byte) { //////////////////////////////////////////////////////////////////////// - func (bc *DummyChain) newBlockState() *state.BlockState { bc.cBlock = &types.Block{ Header: &types.BlockHeader{ PrevBlockHash: bc.bestBlockId[:], BlockNo: bc.bestBlockNo + 1, Timestamp: bc.getTimestamp(), - ChainID: types.MakeChainId(bc.bestBlock.GetHeader().ChainID, bc.HardforkConfig.Version(bc.bestBlockNo + 1)), + ChainID: types.MakeChainId(bc.bestBlock.GetHeader().ChainID, bc.HardforkConfig.Version(bc.bestBlockNo+1)), }, } return state.NewBlockState( @@ -208,7 +207,6 @@ func (bc *DummyChain) newBlockState() *state.BlockState { ) } - func (bc *DummyChain) ExecuteTxs(txs []*types.Tx) ([]*types.Receipt, error) { ex, err := newBlockExecutor(bc, txs) @@ -254,7 +252,7 @@ func newBlockExecutor(bc *DummyChain, txs []*types.Tx) (*blockExecutor, error) { blockState.SetGasPrice(system.GetGasPriceFromState(blockState)) - blockState.Receipts().SetHardFork(bc.HardforkConfig, bc.bestBlockNo + 1) + blockState.Receipts().SetHardFork(bc.HardforkConfig, bc.bestBlockNo+1) return &blockExecutor{ BlockState: blockState, @@ -265,7 +263,7 @@ func newBlockExecutor(bc *DummyChain, txs []*types.Tx) (*blockExecutor, error) { //validatePost: func() error { // return cs.validator.ValidatePost(blockState.GetRoot(), blockState.Receipts(), block) //}, - bi: bi, + bi: bi, }, nil } @@ -285,7 +283,7 @@ func NewTxExecutor(execCtx context.Context, ccc consensus.ChainConsensusCluster, err := executeTx(execCtx, ccc, cdb, blockState, tx, bi, preloadService) if err != nil { - logger.Error().Err(err).Str("hash", enc.ToString(tx.GetHash())).Msg("tx failed") + logger.Error().Err(err).Str("hash", enc.B58Encode(tx.GetHash())).Msg("tx failed") if err2 := blockState.Rollback(blockSnap); err2 != nil { logger.Panic().Err(err).Msg("failed to rollback block state") } @@ -448,21 +446,21 @@ func executeTx( senderState.Balance = amount.Bytes() } } - case types.TxType_FEEDELEGATION: - if balance.Cmp(amount) <= 0 { - // set the balance as = amount - senderState.Balance = amount.Bytes() - } + case types.TxType_FEEDELEGATION: + if balance.Cmp(amount) <= 0 { + // set the balance as = amount + senderState.Balance = amount.Bytes() + } } err = tx.ValidateWithSenderState(senderState, bs.GasPrice, bi.ForkVersion) if err != nil { - err = fmt.Errorf("%w: balance %s, amount %s, gasPrice %s, block %v, txhash: %s", - err, - sender.Balance().String(), - tx.GetBody().GetAmountBigInt().String(), - bs.GasPrice.String(), - bi.No, enc.ToString(tx.GetHash())) + err = fmt.Errorf("%w: balance %s, amount %s, gasPrice %s, block %v, txhash: %s", + err, + sender.Balance().String(), + tx.GetBody().GetAmountBigInt().String(), + bs.GasPrice.String(), + bi.No, enc.B58Encode(tx.GetHash())) return err } @@ -496,7 +494,7 @@ func executeTx( txFee = new(big.Int).SetUint64(0) events, err = executeGovernanceTx(ccc, bs, txBody, sender, receiver, bi) if err != nil { - logger.Warn().Err(err).Str("txhash", enc.ToString(tx.GetHash())).Msg("governance tx Error") + logger.Warn().Err(err).Str("txhash", enc.B58Encode(tx.GetHash())).Msg("governance tx Error") } case types.TxType_FEEDELEGATION: balance := receiver.Balance() @@ -517,7 +515,7 @@ func executeTx( tx.GetHash(), txBody.GetAccount(), txBody.GetAmount()) if err != nil { if err != types.ErrNotAllowedFeeDelegation { - logger.Warn().Err(err).Str("txhash", enc.ToString(tx.GetHash())).Msg("checkFeeDelegation Error") + logger.Warn().Err(err).Str("txhash", enc.B58Encode(tx.GetHash())).Msg("checkFeeDelegation Error") return err } return types.ErrNotAllowedFeeDelegation diff --git a/contract/vm_dummy/vm_dummy.go b/contract/vm_dummy/vm_dummy.go index c1fbce3c6..82cfa8ae6 100644 --- a/contract/vm_dummy/vm_dummy.go +++ b/contract/vm_dummy/vm_dummy.go @@ -477,7 +477,7 @@ func contractFrame(l luaTxContract, bs *state.BlockState, cdb contract.ChainAcce l.Hash(), l.sender(), l.amount().Bytes()) if err != nil { if err != types.ErrNotAllowedFeeDelegation { - logger.Debug().Err(err).Str("txhash", enc.ToString(l.Hash())).Msg("checkFeeDelegation Error") + logger.Debug().Err(err).Str("txhash", enc.B58Encode(l.Hash())).Msg("checkFeeDelegation Error") return err } return types.ErrNotAllowedFeeDelegation diff --git a/internal/enc/base58.go b/internal/enc/base58.go new file mode 100644 index 000000000..363cf5d6a --- /dev/null +++ b/internal/enc/base58.go @@ -0,0 +1,13 @@ +package enc + +import "github.com/mr-tron/base58/base58" + +// B58Encode returns human-readable (base58) string from b. Calling with empty or nil slice returns empty string. +func B58Encode(b []byte) string { + return base58.Encode(b) +} + +// B58Decode returns byte slice from human-readable (base58) string. Calling with empty string returns zero length string error. +func B58Decode(s string) ([]byte, error) { + return base58.Decode(s) +} diff --git a/internal/enc/bstr_test.go b/internal/enc/base58_test.go similarity index 88% rename from internal/enc/bstr_test.go rename to internal/enc/base58_test.go index 8ebf31c7c..4450469e4 100644 --- a/internal/enc/bstr_test.go +++ b/internal/enc/base58_test.go @@ -5,7 +5,7 @@ import ( "testing" ) -func TestToString(t *testing.T) { +func TestB58Encode(t *testing.T) { type args struct { b []byte } @@ -22,13 +22,13 @@ func TestToString(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - got := ToString(tt.args.b) + got := B58Encode(tt.args.b) if got != tt.want { t.Errorf("ToString() = %v, want %v", got, tt.want) } if tt.wantInverse { - got2, err := ToBytes(got) + got2, err := B58Decode(got) if err != nil { t.Errorf("ToBytes() = %s, want no err", err.Error()) } diff --git a/internal/enc/base58check.go b/internal/enc/base58check.go new file mode 100644 index 000000000..723329e38 --- /dev/null +++ b/internal/enc/base58check.go @@ -0,0 +1,13 @@ +package enc + +import ( + "github.com/anaskhan96/base58check" +) + +func B58CheckEncode(version string, data string) (string, error) { + return base58check.Encode(version, data) +} + +func B58CheckDecode(encoded string) (string, error) { + return base58check.Decode(encoded) +} diff --git a/internal/enc/base64.go b/internal/enc/base64.go new file mode 100644 index 000000000..bc755ebd3 --- /dev/null +++ b/internal/enc/base64.go @@ -0,0 +1,11 @@ +package enc + +import "encoding/base64" + +func B64Encode(s []byte) string { + return base64.StdEncoding.EncodeToString(s) +} + +func B64Decode(s string) ([]byte, error) { + return base64.StdEncoding.DecodeString(s) +} diff --git a/internal/enc/bstr.go b/internal/enc/bstr.go deleted file mode 100644 index f5230cc56..000000000 --- a/internal/enc/bstr.go +++ /dev/null @@ -1,13 +0,0 @@ -package enc - -import "github.com/mr-tron/base58/base58" - -// ToString returns human-readable (base58) string from b. Calling with empty or nil slice returns empty string. -func ToString(b []byte) string { - return base58.Encode(b) -} - -// ToBytes returns byte slice from human-readable (base58) string. Calling with empty string returns zero length string error. -func ToBytes(s string) ([]byte, error) { - return base58.Decode(s) -} diff --git a/internal/merkle/merkle_test.go b/internal/merkle/merkle_test.go index 56d1c477f..edc09c497 100644 --- a/internal/merkle/merkle_test.go +++ b/internal/merkle/merkle_test.go @@ -2,13 +2,12 @@ package merkle import ( "bytes" - "encoding/base64" "encoding/binary" "hash" "testing" + "github.com/aergoio/aergo/v2/internal/enc" "github.com/minio/sha256-simd" - "github.com/mr-tron/base58/base58" "github.com/stretchr/testify/assert" ) @@ -16,14 +15,6 @@ var ( tms []MerkleEntry ) -func EncodeB64(bs []byte) string { - return base64.StdEncoding.EncodeToString(bs) -} - -func EncodeB58(bs []byte) string { - return base58.Encode(bs) -} - func beforeTest(count int) error { tms = make([]MerkleEntry, count) @@ -100,7 +91,7 @@ func TestMerkle2Tx(t *testing.T) { for i, merkle := range merkles { assert.Equal(t, len(merkle), 32) - t.Logf("%d:%v", i, EncodeB64(merkle)) + t.Logf("%d:%v", i, enc.B64Encode(merkle)) } } @@ -123,7 +114,7 @@ func TestMerkle3Tx(t *testing.T) { for i, merkle := range merkles { assert.NotNil(t, merkle, "nil=%d", i) assert.Equal(t, len(merkle), 32) - t.Logf("%d:%v", i, EncodeB64(merkle)) + t.Logf("%d:%v", i, enc.B64Encode(merkle)) } } diff --git a/mempool/mempool.go b/mempool/mempool.go index 9a4577301..6a31f80ff 100644 --- a/mempool/mempool.go +++ b/mempool/mempool.go @@ -252,7 +252,7 @@ func (mp *MemPool) Receive(context actor.Context) { Err: errs, }) case *message.MemPoolDelTx: - mp.Info().Str("txhash", enc.ToString(msg.Tx.GetHash())).Msg("remove tx in mempool") + mp.Info().Str("txhash", enc.B58Encode(msg.Tx.GetHash())).Msg("remove tx in mempool") err := mp.removeTx(msg.Tx) context.Respond(&message.MemPoolDelTxRsp{ Err: err, @@ -451,8 +451,8 @@ func (mp *MemPool) setStateDB(block *types.Block) (bool, bool) { } mp.Debug().Str("Hash", newBlockID.String()). Str("StateRoot", types.ToHashID(stateRoot).String()). - Str("chainidhash", enc.ToString(mp.bestChainIdHash)). - Str("next chainidhash", enc.ToString(mp.acceptChainIdHash)). + Str("chainidhash", enc.B58Encode(mp.bestChainIdHash)). + Str("next chainidhash", enc.B58Encode(mp.acceptChainIdHash)). Msg("new StateDB opened") } else if !bytes.Equal(mp.stateDB.GetRoot(), stateRoot) { if err := mp.stateDB.SetRoot(stateRoot); err != nil { @@ -801,7 +801,7 @@ func (mp *MemPool) getAccountState(acc []byte) (*types.State, error) { state, err := mp.stateDB.GetAccountState(types.ToAccountID(acc)) if err != nil { - mp.Fatal().Err(err).Str("sroot", enc.ToString(mp.stateDB.GetRoot())).Msg("failed to get state") + mp.Fatal().Err(err).Str("sroot", enc.B58Encode(mp.stateDB.GetRoot())).Msg("failed to get state") //FIXME PANIC? //mp.Fatal().Err(err).Msg("failed to get state") @@ -959,7 +959,7 @@ func (mp *MemPool) removeTx(tx *types.Tx) error { defer mp.Unlock() if mp.exist(tx.GetHash()) == nil { - mp.Warn().Str("txhash", enc.ToString(tx.GetHash())).Msg("could not find tx to remove") + mp.Warn().Str("txhash", enc.B58Encode(tx.GetHash())).Msg("could not find tx to remove") return types.ErrTxNotFound } acc := tx.GetBody().GetAccount() @@ -969,7 +969,7 @@ func (mp *MemPool) removeTx(tx *types.Tx) error { } newOrphan, removed := list.RemoveTx(tx) if removed == nil { - mp.Error().Str("txhash", enc.ToString(tx.GetHash())).Msg("already removed tx") + mp.Error().Str("txhash", enc.B58Encode(tx.GetHash())).Msg("already removed tx") } mp.orphan += newOrphan mp.releaseMemPoolList(list) diff --git a/mempool/txverifier.go b/mempool/txverifier.go index 76f3e9745..28f311944 100644 --- a/mempool/txverifier.go +++ b/mempool/txverifier.go @@ -31,7 +31,7 @@ func (s *TxVerifier) Receive(context actor.Context) { err = s.mp.put(tx) } if err != nil { - s.mp.Logger.Info().Err(err).Str("txID", enc.ToString(msg.GetHash())).Msg("tx verification failed") + s.mp.Logger.Info().Err(err).Str("txID", enc.B58Encode(msg.GetHash())).Msg("tx verification failed") } } context.Respond(&message.MemPoolPutRsp{Err: err}) diff --git a/p2p/actorwork.go b/p2p/actorwork.go index 84343c4bc..1c301ed83 100644 --- a/p2p/actorwork.go +++ b/p2p/actorwork.go @@ -141,7 +141,7 @@ func (p2ps *P2P) NotifyNewBlock(blockNotice message.NotifyNewBlock) bool { } } - p2ps.Debug().Int("skipped_cnt", skipped).Int("sent_cnt", sent).Str("hash", enc.ToString(blockNotice.Block.BlockHash())).Msg("Notifying new block") + p2ps.Debug().Int("skipped_cnt", skipped).Int("sent_cnt", sent).Str("hash", enc.B58Encode(blockNotice.Block.BlockHash())).Msg("Notifying new block") return true } @@ -162,7 +162,7 @@ func (p2ps *P2P) NotifyBlockProduced(blockNotice message.NotifyNewBlock) bool { } } - p2ps.Debug().Int("skipped_cnt", skipped).Int("sent_cnt", sent).Str("hash", enc.ToString(blockNotice.Block.BlockHash())).Uint64("block_no", req.BlockNo).Msg("Notifying block produced") + p2ps.Debug().Int("skipped_cnt", skipped).Int("sent_cnt", sent).Str("hash", enc.B58Encode(blockNotice.Block.BlockHash())).Uint64("block_no", req.BlockNo).Msg("Notifying block produced") return true } diff --git a/p2p/const_test.go b/p2p/const_test.go index b126be5c8..3e582da0a 100644 --- a/p2p/const_test.go +++ b/p2p/const_test.go @@ -7,7 +7,6 @@ package p2p import ( "bytes" - "encoding/base64" "encoding/hex" "fmt" "testing" @@ -25,7 +24,7 @@ import ( var dummyBlockHash, _ = hex.DecodeString("4f461d85e869ade8a0544f8313987c33a9c06534e50c4ad941498299579bd7ac") var dummyBlockHeight uint64 = 100215 -var dummyTxHash, _ = enc.ToBytes("4H4zAkAyRV253K5SNBJtBxqUgHEbZcXbWFFc6cmQHY45") +var dummyTxHash, _ = enc.B58Decode("4H4zAkAyRV253K5SNBJtBxqUgHEbZcXbWFFc6cmQHY45") var samplePeerID types.PeerID var sampleMeta p2pcommon.PeerMeta @@ -67,9 +66,9 @@ var dummyBestBlock *types.Block var dummyMeta p2pcommon.PeerMeta func init() { - bytes, _ := base64.StdEncoding.DecodeString(sampleKey1PrivBase64) + bytes, _ := enc.B64Decode(sampleKey1PrivBase64) sampleKey1Priv, _ = crypto.UnmarshalPrivateKey(bytes) - bytes, _ = base64.StdEncoding.DecodeString(sampelKey1PubBase64) + bytes, _ = enc.B64Decode(sampelKey1PubBase64) sampleKey1Pub, _ = crypto.UnmarshalPublicKey(bytes) if !sampleKey1Priv.GetPublic().Equals(sampleKey1Pub) { panic("problem in pk generation ") @@ -79,7 +78,7 @@ func init() { panic("problem in id generation") } - bytes, _ = base64.StdEncoding.DecodeString(sampleKey2PrivBase64) + bytes, _ = enc.B64Decode(sampleKey2PrivBase64) sampleKey2Priv, _ = crypto.UnmarshalPrivateKey(bytes) sampleKey2Pub = sampleKey2Priv.GetPublic() sampleKey2ID, _ = types.IDFromPublicKey(sampleKey2Pub) @@ -121,7 +120,7 @@ func init() { sampleTxs = make([][]byte, len(sampleTxsB58)) sampleTxIDs = make([]types.TxID, len(sampleTxsB58)) for i, hashb58 := range sampleTxsB58 { - hash, _ := enc.ToBytes(hashb58) + hash, _ := enc.B58Decode(hashb58) sampleTxs[i] = hash copy(sampleTxIDs[i][:], hash) } @@ -129,7 +128,7 @@ func init() { sampleBlks = make([][]byte, len(sampleBlksB58)) sampleBlksIDs = make([]types.BlockID, len(sampleBlksB58)) for i, hashb58 := range sampleTxsB58 { - hash, _ := enc.ToBytes(hashb58) + hash, _ := enc.B58Decode(hashb58) sampleBlks[i] = hash copy(sampleBlksIDs[i][:], hash) } @@ -149,7 +148,7 @@ func createDummyMo(ctrl *gomock.Controller) *p2pmock.MockMsgOrder { func TestTXIDs(t *testing.T) { for i := 0; i < len(sampleTxIDs); i++ { if !bytes.Equal(sampleTxs[i], sampleTxIDs[i][:]) { - t.Errorf("TX hash %v and converted ID %v are differ.", enc.ToString(sampleTxs[i]), sampleTxIDs[i]) + t.Errorf("TX hash %v and converted ID %v are differ.", enc.B58Encode(sampleTxs[i]), sampleTxIDs[i]) } } } @@ -157,7 +156,7 @@ func TestTXIDs(t *testing.T) { func TestBlockIDs(t *testing.T) { for i := 0; i < len(sampleBlksIDs); i++ { if !bytes.Equal(sampleBlks[i], sampleBlksIDs[i][:]) { - t.Errorf("TX hash %v and converted ID %v are differ.", enc.ToString(sampleBlks[i]), sampleBlksIDs[i]) + t.Errorf("TX hash %v and converted ID %v are differ.", enc.B58Encode(sampleBlks[i]), sampleBlksIDs[i]) } } } @@ -267,12 +266,12 @@ var testIn = []string{ func TestMoreTXIDs(t *testing.T) { for _, in := range testIn { - hash, _ := enc.ToBytes(in) + hash, _ := enc.B58Decode(in) id, err := types.ParseToTxID(hash) if err != nil { - t.Errorf("Failed to parse TX hash %v : %v", enc.ToString(hash), err) + t.Errorf("Failed to parse TX hash %v : %v", enc.B58Encode(hash), err) } else if !bytes.Equal(hash, id[:]) { - t.Errorf("TX hash %v and converted ID %v are differ.", enc.ToString(hash), id) + t.Errorf("TX hash %v and converted ID %v are differ.", enc.B58Encode(hash), id) } } } diff --git a/p2p/hashreceiver_test.go b/p2p/hashreceiver_test.go index ecda5f4e4..c8f57e297 100644 --- a/p2p/hashreceiver_test.go +++ b/p2p/hashreceiver_test.go @@ -120,7 +120,7 @@ func TestBlockHashesReceiver_ReceiveResp(t *testing.T) { for _, h := range arg.Hashes { _, err := types.ParseToBlockID(h) if err != nil { - t.Fatalf("Wrong block hash %s, err %v)", enc.ToString(h), err.Error()) + t.Fatalf("Wrong block hash %s, err %v)", enc.B58Encode(h), err.Error()) } } } diff --git a/p2p/msgorder.go b/p2p/msgorder.go index 5a62a9b84..bd1747db6 100644 --- a/p2p/msgorder.go +++ b/p2p/msgorder.go @@ -169,7 +169,7 @@ func (pr *pbBpNoticeOrder) SendTo(pi p2pcommon.RemotePeer) error { } if pr.trace { p.logger.Debug().Str(p2putil.LogPeerName, p.Name()).Stringer(p2putil.LogProtoID, pr.GetProtocolID()). - Str(p2putil.LogMsgID, pr.GetMsgID().String()).Str(p2putil.LogBlkHash, enc.ToString(pr.block.Hash)).Msg("Notify block produced") + Str(p2putil.LogMsgID, pr.GetMsgID().String()).Str(p2putil.LogBlkHash, enc.B58Encode(pr.block.Hash)).Msg("Notify block produced") } return nil } diff --git a/p2p/p2pkey/nodekey.go b/p2p/p2pkey/nodekey.go index 90dd90d16..9e5d6d013 100644 --- a/p2p/p2pkey/nodekey.go +++ b/p2p/p2pkey/nodekey.go @@ -72,7 +72,7 @@ func InitNodeInfo(baseCfg *config.BaseConfig, p2pCfg *config.P2PConfig, version ni = &nodeInfo{ id: id, - sid: enc.ToString([]byte(id)), + sid: enc.B58Encode([]byte(id)), pubKey: pub, privKey: priv, version: version, diff --git a/p2p/p2putil/certificate_test.go b/p2p/p2putil/certificate_test.go index 11d58d261..135225e3b 100644 --- a/p2p/p2putil/certificate_test.go +++ b/p2p/p2putil/certificate_test.go @@ -51,7 +51,7 @@ func TestNewAgentCertV1(t *testing.T) { t.Errorf("NewAgentCertV1() bpID = %v, want %v", got.AgentID, tt.args.agentID) } if !got.BPPubKey.IsEqual(tt.args.bpKey.PubKey()) { - t.Errorf("NewAgentCertV1() pubKey = %v, want %v", enc.ToString(got.BPPubKey.SerializeCompressed()), enc.ToString(tt.args.bpKey.PubKey().SerializeCompressed())) + t.Errorf("NewAgentCertV1() pubKey = %v, want %v", enc.B58Encode(got.BPPubKey.SerializeCompressed()), enc.B58Encode(tt.args.bpKey.PubKey().SerializeCompressed())) } if !types.IsSamePeerID(got.BPID, tt.args.bpID) { t.Errorf("NewAgentCertV1() bpID = %v, want %v", got.BPID, tt.args.bpID) @@ -258,7 +258,7 @@ func Test_calculateCertificateHash(t *testing.T) { } if !bytes.Equal(h1, h11) { - t.Fatalf("calculated hash is differ! %v , want %v ", enc.ToString(h11), enc.ToString(h1)) + t.Fatalf("calculated hash is differ! %v , want %v ", enc.B58Encode(h11), enc.B58Encode(h1)) } h2, err := calculateCertificateHash(w2) if err != nil { @@ -266,7 +266,7 @@ func Test_calculateCertificateHash(t *testing.T) { } if bytes.Equal(h1, h2) { - t.Fatalf("calculated hash is same! %v , want different ", enc.ToString(h2)) + t.Fatalf("calculated hash is same! %v , want different ", enc.B58Encode(h2)) } } diff --git a/p2p/p2putil/protobuf_test.go b/p2p/p2putil/protobuf_test.go index cc3e10d04..fbf94a9b0 100644 --- a/p2p/p2putil/protobuf_test.go +++ b/p2p/p2putil/protobuf_test.go @@ -15,7 +15,7 @@ import ( "github.com/stretchr/testify/assert" ) -var dummyTxHash, _ = enc.ToBytes("4H4zAkAyRV253K5SNBJtBxqUgHEbZcXbWFFc6cmQHY45") +var dummyTxHash, _ = enc.B58Decode("4H4zAkAyRV253K5SNBJtBxqUgHEbZcXbWFFc6cmQHY45") func Test_MarshalTxResp(t *testing.T) { dummyTx := &types.Tx{Hash: dummyTxHash, Body: &types.TxBody{Payload: []byte("It's a good day to die.")}} diff --git a/p2p/p2putil/util.go b/p2p/p2putil/util.go index 539378821..ab653222a 100644 --- a/p2p/p2putil/util.go +++ b/p2p/p2putil/util.go @@ -186,9 +186,9 @@ func PrintHashList(blocks []*types.Block) string { case 0: return "blk_cnt=0" case 1: - return fmt.Sprintf("blk_cnt=1,hash=%s(num %d)", enc.ToString(blocks[0].Hash), blocks[0].Header.BlockNo) + return fmt.Sprintf("blk_cnt=1,hash=%s(num %d)", enc.B58Encode(blocks[0].Hash), blocks[0].Header.BlockNo) default: - return fmt.Sprintf("blk_cnt=%d,firstHash=%s(num %d),lastHash=%s(num %d)", l, enc.ToString(blocks[0].Hash), blocks[0].Header.BlockNo, enc.ToString(blocks[l-1].Hash), blocks[l-1].Header.BlockNo) + return fmt.Sprintf("blk_cnt=%d,firstHash=%s(num %d),lastHash=%s(num %d)", l, enc.B58Encode(blocks[0].Hash), blocks[0].Header.BlockNo, enc.B58Encode(blocks[l-1].Hash), blocks[l-1].Header.BlockNo) } } diff --git a/p2p/p2putil/util_test.go b/p2p/p2putil/util_test.go index b077f1efe..5f7700578 100644 --- a/p2p/p2putil/util_test.go +++ b/p2p/p2putil/util_test.go @@ -111,10 +111,10 @@ func Test_Encode(t *testing.T) { } for _, test := range tests { t.Run(test.name, func(t *testing.T) { - got := enc.ToString(test.in) + got := enc.B58Encode(test.in) assert.Equal(t, test.out, got) if len(test.out) > 0 { - gotBytes, err := enc.ToBytes(test.out) + gotBytes, err := enc.B58Decode(test.out) assert.Nil(t, err) assert.Equal(t, test.in, gotBytes) } diff --git a/p2p/subproto/block.go b/p2p/subproto/block.go index 79c602ea2..053d65514 100644 --- a/p2p/subproto/block.go +++ b/p2p/subproto/block.go @@ -162,7 +162,7 @@ func (bh *newBlockNoticeHandler) Handle(msg p2pcommon.Message, msgBody p2pcommon if blockID, err := types.ParseToBlockID(data.BlockHash); err != nil { // TODO Add penalty score and break - bh.logger.Info().Str(p2putil.LogPeerName, remotePeer.Name()).Str("hash", enc.ToString(data.BlockHash)).Msg("malformed blockHash") + bh.logger.Info().Str(p2putil.LogPeerName, remotePeer.Name()).Str("hash", enc.B58Encode(data.BlockHash)).Msg("malformed blockHash") return } else { // lru cache can't accept byte slice key @@ -242,7 +242,7 @@ func (bh *getAncestorRequestHandler) handleGetAncestorReq(msg p2pcommon.Message, AncestorNo: ancestor.No, } - bh.logger.Debug().Uint64("ancestorno", ancestor.No).Str("ancestorhash", enc.ToString(ancestor.Hash)).Msg("Sending get ancestor response") + bh.logger.Debug().Uint64("ancestorno", ancestor.No).Str("ancestorhash", enc.B58Encode(ancestor.Hash)).Msg("Sending get ancestor response") remotePeer.SendMessage(remotePeer.MF().NewMsgResponseOrder(msg.ID(), p2pcommon.GetAncestorResponse, resp)) } diff --git a/p2p/subproto/blockhash_test.go b/p2p/subproto/blockhash_test.go index 4dba77a74..a73fabe50 100644 --- a/p2p/subproto/blockhash_test.go +++ b/p2p/subproto/blockhash_test.go @@ -46,7 +46,7 @@ func TestGetHashRequestHandler_handle(t *testing.T) { sampleBlks = make([][]byte, len(sampleBlksB58)) sampleBlksHashes = make([]types.BlockID, len(sampleBlksB58)) for i, hashb58 := range sampleBlksB58 { - hash, _ := enc.ToBytes(hashb58) + hash, _ := enc.B58Decode(hashb58) sampleBlks[i] = hash copy(sampleBlksHashes[i][:], hash) } @@ -154,7 +154,7 @@ func TestGetHashByNoRequestHandler_handle(t *testing.T) { sampleBlks = make([][]byte, len(sampleBlksB58)) sampleBlksHashes = make([]types.BlockID, len(sampleBlksB58)) for i, hashb58 := range sampleBlksB58 { - hash, _ := enc.ToBytes(hashb58) + hash, _ := enc.B58Decode(hashb58) sampleBlks[i] = hash copy(sampleBlksHashes[i][:], hash) } diff --git a/p2p/subproto/bp.go b/p2p/subproto/bp.go index 5cf90f2f1..e92e448e7 100644 --- a/p2p/subproto/bp.go +++ b/p2p/subproto/bp.go @@ -48,7 +48,7 @@ func (h *blockProducedNoticeHandler) Handle(msg p2pcommon.Message, msgBody p2pco block := data.Block if blockID, err := types.ParseToBlockID(data.GetBlock().GetHash()); err != nil { // TODO add penalty score - h.logger.Info().Str(p2putil.LogPeerName, remotePeer.Name()).Str("hash", enc.ToString(data.GetBlock().GetHash())).Msg("malformed blockHash") + h.logger.Info().Str(p2putil.LogPeerName, remotePeer.Name()).Str("hash", enc.B58Encode(data.GetBlock().GetHash())).Msg("malformed blockHash") return } else { bpID, err := block.BPID() @@ -107,7 +107,7 @@ func (h *toAgentBPNoticeHandler) Handle(msg p2pcommon.Message, msgBody p2pcommon block := data.Block if blockID, err := types.ParseToBlockID(data.GetBlock().GetHash()); err != nil { // TODO add penalty score - h.logger.Info().Str(p2putil.LogPeerName, remotePeer.Name()).Str("hash", enc.ToString(data.GetBlock().GetHash())).Msg("malformed blockHash") + h.logger.Info().Str(p2putil.LogPeerName, remotePeer.Name()).Str("hash", enc.B58Encode(data.GetBlock().GetHash())).Msg("malformed blockHash") return } else { bpID, err := block.BPID() diff --git a/p2p/subproto/bp_test.go b/p2p/subproto/bp_test.go index d0e07a7d9..6a35f2ba7 100644 --- a/p2p/subproto/bp_test.go +++ b/p2p/subproto/bp_test.go @@ -65,7 +65,7 @@ func TestNewBlockProducedNoticeHandlerOfBP(t *testing.T) { func Test_blockProducedNoticeHandler_handle_FromBP(t *testing.T) { logger := log.NewLogger("test.subproto") - dummyBlockHash, _ := enc.ToBytes("v6zbuQ4aVSdbTwQhaiZGp5pcL5uL55X3kt2wfxor5W6") + dummyBlockHash, _ := enc.B58Decode("v6zbuQ4aVSdbTwQhaiZGp5pcL5uL55X3kt2wfxor5W6") dummyBlockID := types.MustParseBlockID(dummyBlockHash) bpKey, bpPub, _ := crypto.GenerateKeyPair(crypto.Secp256k1, 256) bpID, _ := types.IDFromPrivateKey(bpKey) diff --git a/p2p/subproto/getblock.go b/p2p/subproto/getblock.go index 4d96e1aee..9e501ff53 100644 --- a/p2p/subproto/getblock.go +++ b/p2p/subproto/getblock.go @@ -82,13 +82,13 @@ func (bh *blockRequestHandler) handleBlkReq(msg p2pcommon.Message, data *types.G foundBlock, err := bh.actor.GetChainAccessor().GetBlock(hash) if err != nil { // the block hash from request must exists. this error is fatal. - bh.logger.Warn().Err(err).Str(p2putil.LogBlkHash, enc.ToString(hash)).Str(p2putil.LogOrgReqID, requestID.String()).Msg("failed to get block while processing getBlock") + bh.logger.Warn().Err(err).Str(p2putil.LogBlkHash, enc.B58Encode(hash)).Str(p2putil.LogOrgReqID, requestID.String()).Msg("failed to get block while processing getBlock") status = types.ResultStatus_INTERNAL break } if foundBlock == nil { // the remote peer request not existing block - bh.logger.Debug().Str(p2putil.LogBlkHash, enc.ToString(hash)).Str(p2putil.LogOrgReqID, requestID.String()).Msg("requested block hash is missing") + bh.logger.Debug().Str(p2putil.LogBlkHash, enc.B58Encode(hash)).Str(p2putil.LogOrgReqID, requestID.String()).Msg("requested block hash is missing") status = types.ResultStatus_NOT_FOUND break diff --git a/p2p/subproto/getblock_test.go b/p2p/subproto/getblock_test.go index 2204087f9..08c557cdf 100644 --- a/p2p/subproto/getblock_test.go +++ b/p2p/subproto/getblock_test.go @@ -95,7 +95,7 @@ func TestBlockResponseHandler_handle(t *testing.T) { logger := log.NewLogger("test.subproto") var dummyPeerID, _ = types.IDB58Decode("16Uiu2HAmN5YU8V2LnTy9neuuJCLNsxLnd5xVSRZqkjvZUHS3mLoD") - dummyBlockHash, _ := enc.ToBytes("v6zbuQ4aVSdbTwQhaiZGp5pcL5uL55X3kt2wfxor5W6") + dummyBlockHash, _ := enc.B58Decode("v6zbuQ4aVSdbTwQhaiZGp5pcL5uL55X3kt2wfxor5W6") var sampleBlksB58 = []string{ "v6zbuQ4aVSdbTwQhaiZGp5pcL5uL55X3kt2wfxor5W6", "2VEPg4MqJUoaS3EhZ6WWSAUuFSuD4oSJ645kSQsGV7H9", @@ -110,7 +110,7 @@ func TestBlockResponseHandler_handle(t *testing.T) { sampleBlks = make([][]byte, len(sampleBlksB58)) sampleBlksHashes = make([]types.BlockID, len(sampleBlksB58)) for i, hashb58 := range sampleBlksB58 { - hash, _ := enc.ToBytes(hashb58) + hash, _ := enc.B58Decode(hashb58) sampleBlks[i] = hash copy(sampleBlksHashes[i][:], hash) } diff --git a/p2p/subproto/ping_test.go b/p2p/subproto/ping_test.go index b6526aa4f..98563483f 100644 --- a/p2p/subproto/ping_test.go +++ b/p2p/subproto/ping_test.go @@ -78,7 +78,7 @@ func Test_pingRequestHandler_handle(t *testing.T) { defer ctrl.Finish() logger := log.NewLogger("test.subproto") - dummyBlockHash, _ := enc.ToBytes("v6zbuQ4aVSdbTwQhaiZGp5pcL5uL55X3kt2wfxor5W6") + dummyBlockHash, _ := enc.B58Decode("v6zbuQ4aVSdbTwQhaiZGp5pcL5uL55X3kt2wfxor5W6") var dummyPeerID, _ = types.IDB58Decode("16Uiu2HAmN5YU8V2LnTy9neuuJCLNsxLnd5xVSRZqkjvZUHS3mLoD") type args struct { diff --git a/p2p/subproto/raftstub.go b/p2p/subproto/raftstub.go index 23c3fb9c5..ed39bd677 100644 --- a/p2p/subproto/raftstub.go +++ b/p2p/subproto/raftstub.go @@ -69,7 +69,7 @@ func (bh *raftNewBlkNoticeDiscardHandler) Handle(msg p2pcommon.Message, msgBody if blockID, err := types.ParseToBlockID(data.BlockHash); err != nil { // TODO Add penalty score and break - bh.logger.Info().Str(p2putil.LogPeerName, remotePeer.Name()).Str("hash", enc.ToString(data.BlockHash)).Msg("malformed blockHash") + bh.logger.Info().Str(p2putil.LogPeerName, remotePeer.Name()).Str("hash", enc.B58Encode(data.BlockHash)).Msg("malformed blockHash") return } else { // just update last status diff --git a/p2p/subproto/tx.go b/p2p/subproto/tx.go index d928f8e77..094dad100 100644 --- a/p2p/subproto/tx.go +++ b/p2p/subproto/tx.go @@ -107,7 +107,7 @@ func (th *newTxNoticeHandler) Handle(msg p2pcommon.Message, msgBody p2pcommon.Me hashes := make([]types.TxID, len(data.TxHashes)) for i, hash := range data.TxHashes { if tid, err := types.ParseToTxID(hash); err != nil { - th.logger.Info().Str(p2putil.LogPeerName, remotePeer.Name()).Str("hash", enc.ToString(hash)).Msg("malformed txhash found") + th.logger.Info().Str(p2putil.LogPeerName, remotePeer.Name()).Str("hash", enc.B58Encode(hash)).Msg("malformed txhash found") // TODO Add penalty score and break break } else { diff --git a/p2p/subproto/tx_test.go b/p2p/subproto/tx_test.go index be9668aec..0ab700b24 100644 --- a/p2p/subproto/tx_test.go +++ b/p2p/subproto/tx_test.go @@ -45,7 +45,7 @@ func BenchmarkArrayKey(b *testing.B) { fmt.Printf("P2 in base64\n") target2 := make(map[string]int) for i := 0; i < size; i++ { - target2[enc.ToString(samples[i][:])] = i + target2[enc.B58Encode(samples[i][:])] = i } endTime := time.Now() fmt.Printf("Takes %f sec\n", endTime.Sub(startTime).Seconds()) diff --git a/p2p/synctx_test.go b/p2p/synctx_test.go index fed5988d7..37270baa5 100644 --- a/p2p/synctx_test.go +++ b/p2p/synctx_test.go @@ -285,7 +285,7 @@ func Test_txSyncManager_refineFrontCacheConsumption(t *testing.T) { } } if w == nil { - t.Fatalf("unexpected sent request %v", enc.ToString(hashes[i])) + t.Fatalf("unexpected sent request %v", enc.B58Encode(hashes[i])) } wTids := w.txIDs if len(hashes) != len(wTids) { @@ -422,7 +422,7 @@ func Test_txSyncManager_refineFrontCache(t *testing.T) { } } if !found { - t.Errorf("req hash %v, is not in wanted hash %v", enc.ToString(hash), tt.wantSend) + t.Errorf("req hash %v, is not in wanted hash %v", enc.B58Encode(hash), tt.wantSend) } sentMap[types.ToTxID(hash)] = 1 } @@ -583,7 +583,7 @@ func Test_syncTxManager_handleTxReq(t *testing.T) { var sampleTxs = make([][]byte, len(sampleTxsB58)) var sampleTxHashes = make([]types.TxID, len(sampleTxsB58)) for i, hashb58 := range sampleTxsB58 { - hash, _ := enc.ToBytes(hashb58) + hash, _ := enc.B58Decode(hashb58) sampleTxs[i] = hash copy(sampleTxHashes[i][:], hash) } diff --git a/p2p/txreceiver.go b/p2p/txreceiver.go index 94c956410..d56addf5e 100644 --- a/p2p/txreceiver.go +++ b/p2p/txreceiver.go @@ -116,7 +116,7 @@ func (br *GetTxsReceiver) handleInWaiting(msg p2pcommon.Message, msgBody p2pcomm } // missing tx for !bytes.Equal(br.hashes[br.offset], tx.Hash) { - br.logger.Trace().Str("expect", enc.ToString(br.hashes[br.offset])).Str("received", enc.ToString(tx.Hash)).Int("offset", br.offset).Msg("expected hash was missing") + br.logger.Trace().Str("expect", enc.B58Encode(br.hashes[br.offset])).Str("received", enc.B58Encode(tx.Hash)).Int("offset", br.offset).Msg("expected hash was missing") br.missed = append(br.missed, tx.Hash) br.offset++ if br.offset >= len(br.hashes) { diff --git a/p2p/v030/v030io_test.go b/p2p/v030/v030io_test.go index e114d0034..4a0929d2d 100644 --- a/p2p/v030/v030io_test.go +++ b/p2p/v030/v030io_test.go @@ -48,7 +48,7 @@ func init() { sampleTxs = make([][]byte, len(sampleTxsB58)) sampleTxHashes = make([]types.TxID, len(sampleTxsB58)) for i, hashb58 := range sampleTxsB58 { - hash, _ := enc.ToBytes(hashb58) + hash, _ := enc.B58Decode(hashb58) sampleTxs[i] = hash copy(sampleTxHashes[i][:], hash) } @@ -56,7 +56,7 @@ func init() { sampleBlks = make([][]byte, len(sampleBlksB58)) sampleBlksHashes = make([]types.BlockID, len(sampleBlksB58)) for i, hashb58 := range sampleTxsB58 { - hash, _ := enc.ToBytes(hashb58) + hash, _ := enc.B58Decode(hashb58) sampleBlks[i] = hash copy(sampleBlksHashes[i][:], hash) } diff --git a/p2p/v030/v032handshake.go b/p2p/v030/v032handshake.go index 803bffc7f..9234c63f3 100644 --- a/p2p/v030/v032handshake.go +++ b/p2p/v030/v032handshake.go @@ -47,7 +47,7 @@ func (h *V032Handshaker) checkRemoteStatus(remotePeerStatus *types.Status) error genHash := h.localGenesisHash if !bytes.Equal(genHash, remotePeerStatus.Genesis) { h.sendGoAway("different genesis block") - return fmt.Errorf("different genesis block local: %v , remote %v", enc.ToString(genHash), enc.ToString(remotePeerStatus.Genesis)) + return fmt.Errorf("different genesis block local: %v , remote %v", enc.B58Encode(genHash), enc.B58Encode(remotePeerStatus.Genesis)) } return nil diff --git a/p2p/v030/v033handshake.go b/p2p/v030/v033handshake.go index ab5399fdf..513c522b6 100644 --- a/p2p/v030/v033handshake.go +++ b/p2p/v030/v033handshake.go @@ -76,7 +76,7 @@ func (h *V033Handshaker) checkRemoteStatus(remotePeerStatus *types.Status) error genHash := h.localGenesisHash if !bytes.Equal(genHash, remotePeerStatus.Genesis) { h.sendGoAway("different genesis block") - return fmt.Errorf("different genesis block local: %v , remote %v", enc.ToString(genHash), enc.ToString(remotePeerStatus.Genesis)) + return fmt.Errorf("different genesis block local: %v , remote %v", enc.B58Encode(genHash), enc.B58Encode(remotePeerStatus.Genesis)) } return nil diff --git a/p2p/v200/v200handshake.go b/p2p/v200/v200handshake.go index 9f35813ef..d9f23c140 100644 --- a/p2p/v200/v200handshake.go +++ b/p2p/v200/v200handshake.go @@ -192,7 +192,7 @@ func (h *V200Handshaker) checkRemoteStatus(remotePeerStatus *types.Status) error genHash := h.localGenesisHash if !bytes.Equal(genHash, remotePeerStatus.Genesis) { h.sendGoAway("different genesis block") - return fmt.Errorf("different genesis block local: %v , remote %v", enc.ToString(genHash), enc.ToString(remotePeerStatus.Genesis)) + return fmt.Errorf("different genesis block local: %v , remote %v", enc.B58Encode(genHash), enc.B58Encode(remotePeerStatus.Genesis)) } h.remoteMeta = rMeta diff --git a/rpc/grpcserver_test.go b/rpc/grpcserver_test.go index 928d88802..d58d129c6 100644 --- a/rpc/grpcserver_test.go +++ b/rpc/grpcserver_test.go @@ -21,31 +21,30 @@ import ( "github.com/aergoio/aergo/v2/pkg/component" "github.com/aergoio/aergo/v2/types" "github.com/golang/mock/gomock" - "github.com/mr-tron/base58/base58" ) func TestAergoRPCService_dummys(t *testing.T) { fmt.Println("dummyBlockHash") fmt.Printf("HEX : %s \n", hex.EncodeToString(dummyBlockHash)) - fmt.Printf("B64 : %s \n", enc.ToString(dummyBlockHash)) - fmt.Printf("B58 : %s \n", base58.Encode(dummyBlockHash)) + fmt.Printf("B64 : %s \n", enc.B64Encode(dummyBlockHash)) + fmt.Printf("B58 : %s \n", enc.B58Encode(dummyBlockHash)) fmt.Println() fmt.Println("dummyTx") fmt.Printf("HEX : %s \n", hex.EncodeToString(dummyTxHash)) - fmt.Printf("B64 : %s \n", enc.ToString(dummyTxHash)) - fmt.Printf("B58 : %s \n", base58.Encode(dummyTxHash)) + fmt.Printf("B64 : %s \n", enc.B64Encode(dummyTxHash)) + fmt.Printf("B58 : %s \n", enc.B58Encode(dummyTxHash)) fmt.Println() fmt.Println("Address1") fmt.Printf("HEX : %s \n", hex.EncodeToString(dummyWalletAddress)) - fmt.Printf("B64 : %s \n", enc.ToString(dummyWalletAddress)) - fmt.Printf("B58 : %s \n", base58.Encode(dummyWalletAddress)) + fmt.Printf("B64 : %s \n", enc.B64Encode(dummyWalletAddress)) + fmt.Printf("B58 : %s \n", enc.B58Encode(dummyWalletAddress)) fmt.Println() fmt.Println("Address2") fmt.Printf("HEX : %s \n", hex.EncodeToString(dummyWalletAddress2)) - fmt.Printf("B64 : %s \n", enc.ToString(dummyWalletAddress2)) - fmt.Printf("B58 : %s \n", base58.Encode(dummyWalletAddress2)) + fmt.Printf("B64 : %s \n", enc.B64Encode(dummyWalletAddress2)) + fmt.Printf("B58 : %s \n", enc.B58Encode(dummyWalletAddress2)) fmt.Println() } @@ -55,8 +54,8 @@ var dummyBlockHeight uint32 = 100215 var dummyTxHash, _ = hex.DecodeString("218bdab4e87fb332b55eb89854ef553f9e3d440c81fff4161b672adede1261ee") // base64 encoding of dummyTxHash is "" -var dummyWalletAddress, _ = base58.Decode("1Ee8uhLFXzkSRRU1orBpgXFAPpVi64aSYo") -var dummyWalletAddress2, _ = base58.Decode("16Uiu2HAkwgfFvViH6j2QpQYKtGKKdveEKZvU2T5mRkqFLTZKU4Vp") +var dummyWalletAddress, _ = enc.B58Decode("1Ee8uhLFXzkSRRU1orBpgXFAPpVi64aSYo") +var dummyWalletAddress2, _ = enc.B58Decode("16Uiu2HAkwgfFvViH6j2QpQYKtGKKdveEKZvU2T5mRkqFLTZKU4Vp") var dummyPayload = []byte("OPreturn I am groooot") var hubStub *component.ComponentHub diff --git a/state/chainstatedb.go b/state/chainstatedb.go index dd5a00eba..a5ade484c 100644 --- a/state/chainstatedb.go +++ b/state/chainstatedb.go @@ -168,8 +168,8 @@ func (sdb *ChainStateDB) UpdateRoot(bstate *BlockState) error { // bstate.BlockInfo.StateRoot = types.ToHashID(sdb.GetRoot()) // } - logger.Debug().Str("before", enc.ToString(sdb.states.GetRoot())). - Str("stateRoot", enc.ToString(bstate.GetRoot())).Msg("apply block state") + logger.Debug().Str("before", enc.B58Encode(sdb.states.GetRoot())). + Str("stateRoot", enc.B58Encode(bstate.GetRoot())).Msg("apply block state") if err := sdb.states.SetRoot(bstate.GetRoot()); err != nil { return err @@ -182,8 +182,8 @@ func (sdb *ChainStateDB) SetRoot(targetBlockRoot []byte) error { sdb.Lock() defer sdb.Unlock() - logger.Debug().Str("before", enc.ToString(sdb.states.GetRoot())). - Str("target", enc.ToString(targetBlockRoot)).Msg("rollback state") + logger.Debug().Str("before", enc.B58Encode(sdb.states.GetRoot())). + Str("target", enc.B58Encode(targetBlockRoot)).Msg("rollback state") sdb.states.SetRoot(targetBlockRoot) return nil diff --git a/state/statedata.go b/state/statedata.go index d4756c603..7cbe94260 100644 --- a/state/statedata.go +++ b/state/statedata.go @@ -1,10 +1,8 @@ package state import ( - "bytes" - "encoding/gob" - "github.com/aergoio/aergo-lib/db" + "github.com/aergoio/aergo/v2/internal/common" "github.com/aergoio/aergo/v2/types" "github.com/golang/protobuf/proto" ) @@ -24,13 +22,7 @@ func saveData(store db.DB, key []byte, data interface{}) error { return err } default: - buffer := &bytes.Buffer{} - enc := gob.NewEncoder(buffer) - err = enc.Encode(data) - if err != nil { - return err - } - raw = buffer.Bytes() + raw, err = common.GobEncode(data) if err != nil { return err } @@ -55,9 +47,7 @@ func loadData(store db.DB, key []byte, data interface{}) error { case proto.Message: err = proto.Unmarshal(raw, data.(proto.Message)) default: - reader := bytes.NewReader(raw) - dec := gob.NewDecoder(reader) - err = dec.Decode(data) + err = common.GobDecode(raw, data) } return err } diff --git a/state/statedb.go b/state/statedb.go index 5f213410b..e77799613 100644 --- a/state/statedb.go +++ b/state/statedb.go @@ -401,7 +401,7 @@ func (states *StateDB) GetVarAndProof(id []byte, root []byte, compressed bool) ( Height: uint32(height), AuditPath: ap, } - logger.Debug().Str("contract root : ", enc.ToString(root)).Msg("Get contract variable and Proof") + logger.Debug().Str("contract root : ", enc.B58Encode(root)).Msg("Get contract variable and Proof") return contractVarProof, nil } @@ -431,7 +431,7 @@ func (states *StateDB) GetAccountAndProof(id []byte, root []byte, compressed boo Height: uint32(height), AuditPath: ap, } - logger.Debug().Str("state root : ", enc.ToString(root)).Msg("Get Account and Proof") + logger.Debug().Str("state root : ", enc.B58Encode(root)).Msg("Get Account and Proof") return accountProof, nil } diff --git a/state/storage.go b/state/storage.go index 2eea7404d..f7ed9e6aa 100644 --- a/state/storage.go +++ b/state/storage.go @@ -134,8 +134,8 @@ func (storage *bufferedStorage) update() error { return err } if !bytes.Equal(before, storage.trie.Root) { - logger.Debug().Str("before", enc.ToString(before)). - Str("after", enc.ToString(storage.trie.Root)).Msg("Changed storage trie root") + logger.Debug().Str("before", enc.B58Encode(before)). + Str("after", enc.B58Encode(storage.trie.Root)).Msg("Changed storage trie root") storage.dirty = true } return nil diff --git a/syncer/blockfetcher.go b/syncer/blockfetcher.go index fbe64018c..92d6016fc 100644 --- a/syncer/blockfetcher.go +++ b/syncer/blockfetcher.go @@ -342,7 +342,7 @@ func (bf *BlockFetcher) checkTaskTimeout() error { return err } - logger.Error().Uint64("StartNo", task.startNo).Str("start", enc.ToString(task.hashes[0])).Int("cout", task.count).Int("runqueue", bf.runningQueue.Len()).Int("pendingqueue", bf.pendingQueue.Len()). + logger.Error().Uint64("StartNo", task.startNo).Str("start", enc.B58Encode(task.hashes[0])).Int("cout", task.count).Int("runqueue", bf.runningQueue.Len()).Int("pendingqueue", bf.pendingQueue.Len()). Msg("timeouted task pushed to pending queue") //time.Sleep(10000*time.Second) @@ -358,7 +358,7 @@ func (bf *BlockFetcher) processFailedTask(task *FetchTask, isErr bool) error { } } - logger.Error().Int("peerno", task.syncPeer.No).Uint64("StartNo", task.startNo).Str("start", enc.ToString(task.hashes[0])).Msg("task fail, move to retry queue") + logger.Error().Int("peerno", task.syncPeer.No).Uint64("StartNo", task.startNo).Str("start", enc.B58Encode(task.hashes[0])).Msg("task fail, move to retry queue") failPeer := task.syncPeer @@ -380,7 +380,7 @@ func (bf *BlockFetcher) processFailedTask(task *FetchTask, isErr bool) error { } func (bf *BlockFetcher) popNextTask(task *FetchTask) { - logger.Debug().Int("retry", task.retry).Uint64("StartNo", task.startNo).Str("start", enc.ToString(task.hashes[0])).Str("end", enc.ToString(task.hashes[task.count-1])). + logger.Debug().Int("retry", task.retry).Uint64("StartNo", task.startNo).Str("start", enc.B58Encode(task.hashes[0])).Str("end", enc.B58Encode(task.hashes[task.count-1])). Int("tasks retry", bf.retryQueue.Len()).Int("tasks pending", bf.pendingQueue.Len()).Msg("next fetchtask") var poppedTask *FetchTask @@ -427,7 +427,7 @@ func (bf *BlockFetcher) searchCandidateTask() (*FetchTask, error) { start, end := 0, 0 count := hashSet.Count - logger.Debug().Uint64("startno", hashSet.StartNo).Str("start", enc.ToString(hashSet.Hashes[0])).Int("count", hashSet.Count).Msg("add new fetchtasks from HashSet") + logger.Debug().Uint64("startno", hashSet.StartNo).Str("start", enc.B58Encode(hashSet.Hashes[0])).Int("count", hashSet.Count).Msg("add new fetchtasks from HashSet") for start < count { end = start + bf.maxFetchSize @@ -464,7 +464,7 @@ func (bf *BlockFetcher) searchCandidateTask() (*FetchTask, error) { return nil, nil } - logger.Debug().Uint64("startno", hashSet.StartNo).Array("hashes", &LogBlockHashesMarshaller{hashSet.Hashes, 10}).Str("start", enc.ToString(hashSet.Hashes[0])).Int("count", hashSet.Count).Msg("BlockFetcher got hashset") + logger.Debug().Uint64("startno", hashSet.StartNo).Array("hashes", &LogBlockHashesMarshaller{hashSet.Hashes, 10}).Str("start", enc.B58Encode(hashSet.Hashes[0])).Int("count", hashSet.Count).Msg("BlockFetcher got hashset") bf.curHashSet = hashSet addNewFetchTasks(hashSet) @@ -488,12 +488,12 @@ func (m LogBlockHashesMarshaller) MarshalZerologArray(a *zerolog.Array) { size := len(m.arr) if size > m.limit { for i := 0; i < m.limit-1; i++ { - a.Str(enc.ToString(m.arr[i])) + a.Str(enc.B58Encode(m.arr[i])) } a.Str(fmt.Sprintf("(and %d more)", size-m.limit+1)) } else { for _, element := range m.arr { - a.Str(enc.ToString(element)) + a.Str(enc.B58Encode(element)) } } } @@ -533,7 +533,7 @@ func (bf *BlockFetcher) runTask(task *FetchTask, peer *SyncPeer) { task.syncPeer = peer bf.runningQueue.PushBack(task) - logger.Debug().Int("peerno", task.syncPeer.No).Int("count", task.count).Uint64("StartNo", task.startNo).Str("start", enc.ToString(task.hashes[0])).Int("runqueue", bf.runningQueue.Len()).Msg("send block fetch request") + logger.Debug().Int("peerno", task.syncPeer.No).Int("count", task.count).Uint64("StartNo", task.startNo).Str("start", enc.B58Encode(task.hashes[0])).Int("runqueue", bf.runningQueue.Len()).Msg("send block fetch request") bf.compRequester.TellTo(message.P2PSvc, &message.GetBlockChunks{Seq: bf.GetSeq(), GetBlockInfos: message.GetBlockInfos{ToWhom: peer.ID, Hashes: task.hashes}, TTL: DfltFetchTimeOut}) } @@ -553,7 +553,7 @@ func (bf *BlockFetcher) findFinished(msg *message.GetBlockChunksRsp, peerMatch b if task.isPeerMatched(msg.ToWhom) { bf.runningQueue.Remove(e) - logger.Debug().Stringer("peer", types.LogPeerShort(msg.ToWhom)).Err(msg.Err).Str("start", enc.ToString(task.hashes[0])).Int("count", task.count).Int("runqueue", bf.runningQueue.Len()).Msg("task finished with error") + logger.Debug().Stringer("peer", types.LogPeerShort(msg.ToWhom)).Err(msg.Err).Str("start", enc.B58Encode(task.hashes[0])).Int("count", task.count).Int("runqueue", bf.runningQueue.Len()).Msg("task finished with error") return task, nil } } else { @@ -561,7 +561,7 @@ func (bf *BlockFetcher) findFinished(msg *message.GetBlockChunksRsp, peerMatch b if task.isMatched(msg.ToWhom, msg.Blocks, count) { bf.runningQueue.Remove(e) - logger.Debug().Uint64("StartNo", task.startNo).Str("start", enc.ToString(task.hashes[0])).Int("count", task.count).Int("runqueue", bf.runningQueue.Len()). + logger.Debug().Uint64("StartNo", task.startNo).Str("start", enc.B58Encode(task.hashes[0])).Int("count", task.count).Int("runqueue", bf.runningQueue.Len()). Msg("task finished") return task, nil @@ -737,7 +737,7 @@ func (tq *TaskQueue) Peek() *FetchTask { func (task *FetchTask) isTimeOut(now time.Time, timeout time.Duration) bool { if now.Sub(task.started) > timeout { - logger.Info().Int("peerno", task.syncPeer.No).Uint64("startno", task.startNo).Str("start", enc.ToString(task.hashes[0])).Int("cout", task.count).Msg("FetchTask peer timeouted") + logger.Info().Int("peerno", task.syncPeer.No).Uint64("startno", task.startNo).Str("start", enc.B58Encode(task.hashes[0])).Int("cout", task.count).Msg("FetchTask peer timeouted") return true } @@ -756,7 +756,7 @@ func (task *FetchTask) isMatched(peerID types.PeerID, blocks []*types.Block, cou for i, block := range blocks { if bytes.Compare(task.hashes[i], block.GetHash()) != 0 { - logger.Info().Int("peerno", task.syncPeer.No).Str("hash", enc.ToString(task.hashes[0])).Int("idx", i).Msg("task hash mismatch") + logger.Info().Int("peerno", task.syncPeer.No).Str("hash", enc.B58Encode(task.hashes[0])).Int("idx", i).Msg("task hash mismatch") return false } } diff --git a/syncer/blockprocessor.go b/syncer/blockprocessor.go index b533bc49c..4dfc26aef 100644 --- a/syncer/blockprocessor.go +++ b/syncer/blockprocessor.go @@ -136,8 +136,8 @@ func (bproc *BlockProcessor) GetBlockChunkRsp(msg *message.GetBlockChunksRsp) er //TODO invalid peer logger.Error().Stringer("peer", types.LogPeerShort(msg.ToWhom)). Int("count", len(msg.Blocks)). - Str("from", enc.ToString(msg.Blocks[0].GetHash())). - Str("to", enc.ToString(msg.Blocks[len(msg.Blocks)-1].GetHash())). + Str("from", enc.B58Encode(msg.Blocks[0].GetHash())). + Str("to", enc.B58Encode(msg.Blocks[len(msg.Blocks)-1].GetHash())). Msg("dropped unknown block response message") return nil } @@ -172,7 +172,7 @@ func (bproc *BlockProcessor) GetBlockChunkRspError(msg *message.GetBlockChunksRs func (bproc *BlockProcessor) AddBlockResponse(msg *message.AddBlockRsp) error { if err := bproc.isValidResponse(msg); err != nil { - logger.Info().Err(err).Uint64("no", msg.BlockNo).Str("hash", enc.ToString(msg.BlockHash)).Msg("block connect failed") + logger.Info().Err(err).Uint64("no", msg.BlockNo).Str("hash", enc.B58Encode(msg.BlockHash)).Msg("block connect failed") return err } @@ -182,12 +182,12 @@ func (bproc *BlockProcessor) AddBlockResponse(msg *message.AddBlockRsp) error { if curNo != msg.BlockNo || !bytes.Equal(curHash, msg.BlockHash) { logger.Error().Uint64("curNo", curNo).Uint64("msgNo", msg.BlockNo). - Str("curHash", enc.ToString(curHash)).Str("msgHash", enc.ToString(msg.BlockHash)). + Str("curHash", enc.B58Encode(curHash)).Str("msgHash", enc.B58Encode(msg.BlockHash)). Msg("invalid add block response") return &ErrSyncMsg{msg: msg, str: "drop unknown add response"} } - logger.Info().Uint64("no", msg.BlockNo).Str("hash", enc.ToString(msg.BlockHash)).Msg("block connect succeed") + logger.Info().Uint64("no", msg.BlockNo).Str("hash", enc.B58Encode(msg.BlockHash)).Msg("block connect succeed") bproc.blockFetcher.stat.setLastAddBlock(curBlock) @@ -266,7 +266,7 @@ func (bproc *BlockProcessor) connectBlock(block *types.Block) { } logger.Info().Uint64("no", block.GetHeader().BlockNo). - Str("hash", enc.ToString(block.GetHash())). + Str("hash", enc.B58Encode(block.GetHash())). Msg("request connecting block to chainsvc") bproc.compRequester.RequestTo(message.ChainSvc, &message.AddBlock{PeerID: "", Block: block, Bstate: nil, IsSync: true}) @@ -283,7 +283,7 @@ func (bproc *BlockProcessor) pushToConnQueue(newReq *ConnectTask) { bproc.connQueue = sortedList logger.Info().Int("len", len(bproc.connQueue)).Uint64("firstno", newReq.firstNo). - Str("firstHash", enc.ToString(newReq.Blocks[0].GetHash())). + Str("firstHash", enc.B58Encode(newReq.Blocks[0].GetHash())). Msg("add new task to connect queue") } @@ -307,7 +307,7 @@ func (bproc *BlockProcessor) popFromConnQueue() *ConnectTask { bproc.connQueue = sortedList logger.Info().Int("len", len(sortedList)).Uint64("firstno", newReq.firstNo). - Str("firstHash", enc.ToString(newReq.Blocks[0].GetHash())). + Str("firstHash", enc.B58Encode(newReq.Blocks[0].GetHash())). Msg("pop task from connect queue") return newReq diff --git a/syncer/finder.go b/syncer/finder.go index 70a179a38..d0ab54d65 100644 --- a/syncer/finder.go +++ b/syncer/finder.go @@ -140,7 +140,7 @@ func (finder *Finder) lightscan() (*types.BlockInfo, error) { if ancestor == nil { logger.Debug().Msg("not found ancestor in lightscan") } else { - logger.Info().Str("hash", enc.ToString(ancestor.Hash)).Uint64("no", ancestor.No).Msg("find ancestor in lightscan") + logger.Info().Str("hash", enc.B58Encode(ancestor.Hash)).Uint64("no", ancestor.No).Msg("find ancestor in lightscan") if ancestor.No >= finder.ctx.TargetNo { logger.Info().Msg("already synchronized") @@ -163,7 +163,7 @@ func (finder *Finder) getAnchors() ([][]byte, error) { finder.ctx.LastAnchor = result.(message.GetAnchorsRsp).LastNo } - logger.Info().Str("start", enc.ToString(anchors[0])).Int("count", len(anchors)).Uint64("last", finder.ctx.LastAnchor).Msg("get anchors from chain") + logger.Info().Str("start", enc.B58Encode(anchors[0])).Int("count", len(anchors)).Uint64("last", finder.ctx.LastAnchor).Msg("get anchors from chain") return anchors, nil } @@ -204,7 +204,7 @@ func (finder *Finder) fullscan() (*types.BlockInfo, error) { if ancestor == nil { logger.Info().Msg("failed to search ancestor in fullscan") } else { - logger.Info().Uint64("no", ancestor.No).Str("hash", enc.ToString(ancestor.Hash)).Msg("find ancestor in fullscan") + logger.Info().Uint64("no", ancestor.No).Str("hash", enc.B58Encode(ancestor.Hash)).Msg("find ancestor in fullscan") } return ancestor, err diff --git a/syncer/hashfetcher.go b/syncer/hashfetcher.go index 3892bd130..66ea2a076 100644 --- a/syncer/hashfetcher.go +++ b/syncer/hashfetcher.go @@ -171,7 +171,7 @@ func (hf *HashFetcher) requestHashSet() { hf.reqTime = time.Now() hf.isRequesting = true - logger.Debug().Uint64("prev", hf.lastBlockInfo.No).Str("prevhash", enc.ToString(hf.lastBlockInfo.Hash)).Uint64("count", count).Msg("request hashset to peer") + logger.Debug().Uint64("prev", hf.lastBlockInfo.No).Str("prevhash", enc.B58Encode(hf.lastBlockInfo.Hash)).Uint64("count", count).Msg("request hashset to peer") hf.compRequester.TellTo(message.P2PSvc, &message.GetHashes{Seq: hf.GetSeq(), ToWhom: hf.ctx.PeerID, PrevInfo: hf.lastBlockInfo, Count: count}) } @@ -241,8 +241,8 @@ func (hf *HashFetcher) isValidResponse(msg *message.GetHashesRsp) (bool, error) } if !isValid { - logger.Error().Str("req prev", enc.ToString(hf.lastBlockInfo.Hash)). - Str("msg prev", enc.ToString(msg.PrevInfo.Hash)). + logger.Error().Str("req prev", enc.B58Encode(hf.lastBlockInfo.Hash)). + Str("msg prev", enc.B58Encode(msg.PrevInfo.Hash)). Uint64("req count", hf.reqCount). Uint64("msg count", msg.Count). Msg("invalid GetHashesRsp") @@ -267,8 +267,8 @@ func (hf *HashFetcher) GetHahsesRsp(msg *message.GetHashesRsp) { logger.Debug().Int("count", count). Uint64("prev", msg.PrevInfo.No). - Str("start", enc.ToString(msg.Hashes[0])). - Str("end", enc.ToString(msg.Hashes[count-1])).Msg("receive GetHashesRsp") + Str("start", enc.B58Encode(msg.Hashes[0])). + Str("end", enc.B58Encode(msg.Hashes[count-1])).Msg("receive GetHashesRsp") hf.responseCh <- msg return diff --git a/types/account.go b/types/account.go index 2512ca8cd..550d993e5 100644 --- a/types/account.go +++ b/types/account.go @@ -6,7 +6,7 @@ import ( "fmt" "strings" - "github.com/anaskhan96/base58check" + "github.com/aergoio/aergo/v2/internal/enc" ) const AddressLength = 33 @@ -50,7 +50,7 @@ func EncodeAddress(addr Address) string { if len(addr) != AddressLength { return string(addr) } - encoded, _ := base58check.Encode(fmt.Sprintf("%x", AddressVersion), hex.EncodeToString(addr)) + encoded, _ := enc.B58CheckEncode(fmt.Sprintf("%x", AddressVersion), hex.EncodeToString(addr)) return encoded } @@ -68,7 +68,7 @@ func DecodeAddress(encodedAddr string) (Address, error) { } return []byte(name), nil } - decodedString, err := base58check.Decode(encodedAddr) + decodedString, err := enc.B58CheckDecode(encodedAddr) if err != nil { return nil, err } @@ -95,12 +95,12 @@ func DecodeAddressBytes(decodedBytes []byte) (Address, error) { } func EncodePrivKey(key []byte) string { - encoded, _ := base58check.Encode(fmt.Sprintf("%x", PrivKeyVersion), hex.EncodeToString(key)) + encoded, _ := enc.B58CheckEncode(fmt.Sprintf("%x", PrivKeyVersion), hex.EncodeToString(key)) return encoded } func DecodePrivKey(encodedKey string) ([]byte, error) { - decodedString, err := base58check.Decode(encodedKey) + decodedString, err := enc.B58CheckDecode(encodedKey) if err != nil { return nil, err } diff --git a/types/blockchain.go b/types/blockchain.go index 3de9e1bf3..6cd7f9131 100644 --- a/types/blockchain.go +++ b/types/blockchain.go @@ -452,14 +452,14 @@ func (block *Block) BPID2Str() string { return "" } - return enc.ToString([]byte(id)) + return enc.B58Encode([]byte(id)) } // ID returns the base64 encoded formated ID (hash) of block. func (block *Block) ID() string { hash := block.BlockHash() if hash != nil { - return enc.ToString(hash) + return enc.B58Encode(hash) } return "" @@ -470,7 +470,7 @@ func (block *Block) ID() string { func (block *Block) PrevID() string { hash := block.GetHeader().GetPrevBlockHash() if hash != nil { - return enc.ToString(hash) + return enc.B58Encode(hash) } return "" diff --git a/types/common.go b/types/common.go index b25aeaa6c..783290cbd 100644 --- a/types/common.go +++ b/types/common.go @@ -1,9 +1,7 @@ package types import ( - "encoding/base64" - - "github.com/mr-tron/base58/base58" + "github.com/aergoio/aergo/v2/internal/enc" ) const MAXBLOCKNO BlockNo = 18446744073709551615 @@ -11,20 +9,20 @@ const maxMetaSizeLimit = uint32(256 << 10) const blockSizeHardLimit = uint32(8 << (10 * 2)) func EncodeB64(bs []byte) string { - return base64.StdEncoding.EncodeToString(bs) + return enc.B64Encode(bs) } func DecodeB64(sb string) []byte { - buf, _ := base64.StdEncoding.DecodeString(sb) + buf, _ := enc.B64Decode(sb) return buf } func EncodeB58(bs []byte) string { - return base58.Encode(bs) + return enc.B58Encode(bs) } func DecodeB58(sb string) []byte { - buf, _ := base58.Decode(sb) + buf, _ := enc.B58Decode(sb) return buf } diff --git a/types/genesis_test.go b/types/genesis_test.go index d464648e3..0da7cba65 100644 --- a/types/genesis_test.go +++ b/types/genesis_test.go @@ -36,7 +36,7 @@ func TestGenesisChainID(t *testing.T) { a.Nil(err) a.True(g.ID.Equals(&defaultChainID)) fmt.Println("len:", len(chainID)) - fmt.Println("chain_id: ", enc.ToString(chainID)) + fmt.Println("chain_id: ", enc.B58Encode(chainID)) } func TestGenesisBytes(t *testing.T) { diff --git a/types/logging.go b/types/logging.go index 329b24c40..91154797c 100644 --- a/types/logging.go +++ b/types/logging.go @@ -7,6 +7,7 @@ package types import ( "fmt" + "github.com/aergoio/aergo/v2/internal/enc" "github.com/rs/zerolog" ) @@ -16,7 +17,7 @@ type LogTxHash struct { } func (t LogTxHash) MarshalZerologObject(e *zerolog.Event) { - e.Str("txID", enc.ToString(t.Hash)) + e.Str("txID", enc.B58Encode(t.Hash)) } type LogTx struct { @@ -24,7 +25,7 @@ type LogTx struct { } func (t LogTx) MarshalZerologObject(e *zerolog.Event) { - e.Str("txID", enc.ToString(t.GetHash())).Str("account", enc.ToString(t.Body.Account)).Uint64("nonce", t.Body.Nonce) + e.Str("txID", enc.B58Encode(t.GetHash())).Str("account", enc.B58Encode(t.Body.Account)).Uint64("nonce", t.Body.Nonce) } type LogTrsactions struct { @@ -63,7 +64,7 @@ func marshalTrx(tr Transaction, a *zerolog.Array) { type LogBase58 []byte func (t LogBase58) String() string { - return enc.ToString(t) + return enc.B58Encode(t) } // LogAddr is thin wrapper which show base58 encoded form of wallet or smart contract diff --git a/types/logging_test.go b/types/logging_test.go index 7c1bfb964..f21ccbef2 100644 --- a/types/logging_test.go +++ b/types/logging_test.go @@ -1,10 +1,11 @@ package types import ( + "testing" + "github.com/aergoio/aergo-lib/log" "github.com/aergoio/aergo/v2/internal/enc" "github.com/rs/zerolog" - "testing" ) func BenchmarkLogMemAllocationCompared(b *testing.B) { @@ -69,7 +70,7 @@ func BenchmarkLogMemAllocationRunD(b *testing.B) { type LogB58Wrapper []byte func (t LogB58Wrapper) MarshalZerologObject(e *zerolog.Event) { - e.Str("b58", enc.ToString(t)) + e.Str("b58", enc.B58Encode(t)) } func BenchmarkLogMemAllocationWrapper(b *testing.B) { diff --git a/types/p2p_test.go b/types/p2p_test.go index ef88473af..d935b1942 100644 --- a/types/p2p_test.go +++ b/types/p2p_test.go @@ -16,7 +16,7 @@ import ( ) func TestUnmarshalSize(t *testing.T) { - var dummyTxHash, _ = enc.ToBytes("4H4zAkAyRV253K5SNBJtBxqUgHEbZcXbWFFc6cmQHY45") + var dummyTxHash, _ = enc.B58Decode("4H4zAkAyRV253K5SNBJtBxqUgHEbZcXbWFFc6cmQHY45") fmt.Println("Hash: ", hex.EncodeToString(dummyTxHash)) sample := &NewTransactionsNotice{} diff --git a/types/p2plogging.go b/types/p2plogging.go index 0b25b1d8d..c4364a44a 100644 --- a/types/p2plogging.go +++ b/types/p2plogging.go @@ -34,12 +34,12 @@ func (m LogB58EncMarshaller) MarshalZerologArray(a *zerolog.Array) { size := len(m.arr) if size > m.limit { for i := 0; i < m.limit-1; i++ { - a.Str(enc.ToString(m.arr[i])) + a.Str(enc.B58Encode(m.arr[i])) } a.Str(fmt.Sprintf("(and %d more)", size-m.limit+1)) } else { for _, element := range m.arr { - a.Str(enc.ToString(element)) + a.Str(enc.B58Encode(element)) } } } @@ -53,12 +53,12 @@ func (m LogBlockHashMarshaller) MarshalZerologArray(a *zerolog.Array) { size := len(m.arr) if size > m.limit { for i := 0; i < m.limit-1; i++ { - a.Str(enc.ToString(m.arr[i].GetHash())) + a.Str(enc.B58Encode(m.arr[i].GetHash())) } a.Str(fmt.Sprintf("(and %d more)", size-m.limit+1)) } else { for _, element := range m.arr { - a.Str(enc.ToString(element.GetHash())) + a.Str(enc.B58Encode(element.GetHash())) } } } @@ -134,15 +134,15 @@ func (m *NewTransactionsNotice) MarshalZerologObject(e *zerolog.Event) { } func (m *BlockProducedNotice) MarshalZerologObject(e *zerolog.Event) { - e.Str("bp", enc.ToString(m.ProducerID)).Uint64(LogBlkNo, m.BlockNo).Str(LogBlkHash, enc.ToString(m.Block.Hash)) + e.Str("bp", enc.B58Encode(m.ProducerID)).Uint64(LogBlkNo, m.BlockNo).Str(LogBlkHash, enc.B58Encode(m.Block.Hash)) } func (m *Ping) MarshalZerologObject(e *zerolog.Event) { - e.Str(LogBlkHash, enc.ToString(m.BestBlockHash)).Uint64(LogBlkNo, m.BestHeight) + e.Str(LogBlkHash, enc.B58Encode(m.BestBlockHash)).Uint64(LogBlkNo, m.BestHeight) } func (m *GetHashesRequest) MarshalZerologObject(e *zerolog.Event) { - e.Str("prev_hash", enc.ToString(m.PrevHash)).Uint64("prev_no", m.PrevNumber) + e.Str("prev_hash", enc.B58Encode(m.PrevHash)).Uint64("prev_no", m.PrevNumber) } func (m *GetHashesResponse) MarshalZerologObject(e *zerolog.Event) { @@ -150,7 +150,7 @@ func (m *GetHashesResponse) MarshalZerologObject(e *zerolog.Event) { } func (m *GetBlockHeadersRequest) MarshalZerologObject(e *zerolog.Event) { - e.Str(LogBlkHash, enc.ToString(m.Hash)).Uint64(LogBlkNo, m.Height).Bool("ascending", m.Asc).Uint32("size", m.Size) + e.Str(LogBlkHash, enc.B58Encode(m.Hash)).Uint64(LogBlkNo, m.Height).Bool("ascending", m.Asc).Uint32("size", m.Size) } func (m *GetBlockHeadersResponse) MarshalZerologObject(e *zerolog.Event) { @@ -162,7 +162,7 @@ func (m *GetHashByNo) MarshalZerologObject(e *zerolog.Event) { } func (m *GetHashByNoResponse) MarshalZerologObject(e *zerolog.Event) { - e.Str(LogRespStatus, m.Status.String()).Str(LogBlkHash, enc.ToString(m.BlockHash)) + e.Str(LogRespStatus, m.Status.String()).Str(LogBlkHash, enc.B58Encode(m.BlockHash)) } func (m *GetAncestorRequest) MarshalZerologObject(e *zerolog.Event) { @@ -170,15 +170,15 @@ func (m *GetAncestorRequest) MarshalZerologObject(e *zerolog.Event) { } func (m *GetAncestorResponse) MarshalZerologObject(e *zerolog.Event) { - e.Str(LogRespStatus, m.Status.String()).Str(LogBlkHash, enc.ToString(m.AncestorHash)).Uint64(LogBlkNo, m.AncestorNo) + e.Str(LogRespStatus, m.Status.String()).Str(LogBlkHash, enc.B58Encode(m.AncestorHash)).Uint64(LogBlkNo, m.AncestorNo) } func (m *GetClusterInfoRequest) MarshalZerologObject(e *zerolog.Event) { - e.Str("best_hash", enc.ToString(m.BestBlockHash)) + e.Str("best_hash", enc.B58Encode(m.BestBlockHash)) } func (m *GetClusterInfoResponse) MarshalZerologObject(e *zerolog.Event) { - e.Str(LogChainID, enc.ToString(m.ChainID)).Str("err", m.Error).Array("members", RaftMbrsMarshaller{arr: m.MbrAttrs, limit: 10}).Uint64("cluster_id", m.ClusterID) + e.Str(LogChainID, enc.B58Encode(m.ChainID)).Str("err", m.Error).Array("members", RaftMbrsMarshaller{arr: m.MbrAttrs, limit: 10}).Uint64("cluster_id", m.ClusterID) } func (m *IssueCertificateResponse) MarshalZerologObject(e *zerolog.Event) { diff --git a/types/receipt.go b/types/receipt.go index 524243b16..4155e2928 100644 --- a/types/receipt.go +++ b/types/receipt.go @@ -352,7 +352,7 @@ func (r *Receipt) MarshalJSON() ([]byte, error) { b.WriteString(`{"BlockNo":`) b.WriteString(fmt.Sprintf("%d", r.BlockNo)) b.WriteString(`,"BlockHash":"`) - b.WriteString(enc.ToString(r.BlockHash)) + b.WriteString(enc.B58Encode(r.BlockHash)) b.WriteString(`","contractAddress":"`) b.WriteString(EncodeAddress(r.ContractAddress)) b.WriteString(`","status":"`) @@ -368,7 +368,7 @@ func (r *Receipt) MarshalJSON() ([]byte, error) { b.WriteString(r.Ret) } b.WriteString(`,"txHash":"`) - b.WriteString(enc.ToString(r.TxHash)) + b.WriteString(enc.B58Encode(r.TxHash)) b.WriteString(`","txIndex":`) b.WriteString(fmt.Sprintf("%d", r.TxIndex)) b.WriteString(`,"from":"`) @@ -731,11 +731,11 @@ func (ev *Event) MarshalJSON() ([]byte, error) { b.WriteString(`","Args":`) b.WriteString(ev.JsonArgs) b.WriteString(`,"txHash":"`) - b.WriteString(enc.ToString(ev.TxHash)) + b.WriteString(enc.B58Encode(ev.TxHash)) b.WriteString(`","EventIdx":`) b.WriteString(fmt.Sprintf("%d", ev.EventIdx)) b.WriteString(`,"BlockHash":"`) - b.WriteString(enc.ToString(ev.BlockHash)) + b.WriteString(enc.B58Encode(ev.BlockHash)) b.WriteString(`","BlockNo":`) b.WriteString(fmt.Sprintf("%d", ev.BlockNo)) b.WriteString(`,"TxIndex":`) diff --git a/types/state.go b/types/state.go index c33577631..5ee622ed8 100644 --- a/types/state.go +++ b/types/state.go @@ -58,7 +58,7 @@ func ToHashID(hash []byte) HashID { return HashID(buf) } func (id HashID) String() string { - return enc.ToString(id[:]) + return enc.B58Encode(id[:]) } // Bytes make a byte slice from id diff --git a/types/transaction.go b/types/transaction.go index 61fac049f..cc81c1104 100644 --- a/types/transaction.go +++ b/types/transaction.go @@ -8,8 +8,8 @@ import ( "strings" "github.com/aergoio/aergo/v2/fee" + "github.com/aergoio/aergo/v2/internal/enc" "github.com/golang/protobuf/proto" - "github.com/mr-tron/base58/base58" ) //governance type transaction which has aergo.system in recipient @@ -203,7 +203,7 @@ func ValidateSystemTx(tx *TxBody) error { return ErrTxInvalidPayload } unique[encoded]++ - candidate, err := base58.Decode(encoded) + candidate, err := enc.B58Decode(encoded) if err != nil { return ErrTxInvalidPayload } From 5709ea01b76214c58e3014fca94e53858b86a0c7 Mon Sep 17 00:00:00 2001 From: kch Date: Fri, 3 Nov 2023 04:56:40 +0000 Subject: [PATCH 2/6] replace hex to internal function --- account/key/crypto/v1strategy.go | 18 +++++++++--------- cmd/aergocli/cmd/blockchain_test.go | 3 +-- cmd/aergocli/cmd/contract.go | 3 +-- cmd/aergocli/util/base64ToHex.go | 6 +++--- cmd/aergoluac/encoding/codeEncoding.go | 5 ++--- contract/ethstorageproof.go | 8 ++++---- contract/ethstorageproof_test.go | 7 ++++--- contract/hook_dbg.go | 6 +++--- contract/vm.go | 3 +-- contract/vm_callback.go | 11 +++++------ internal/enc/hex.go | 11 +++++++++++ p2p/const_test.go | 3 +-- p2p/p2putil/PKTest_test.go | 10 +++++----- p2p/p2putil/cryptoutil_test.go | 10 +++++----- p2p/p2putil/protobuf_test.go | 6 +++--- p2p/transport/networktransport_test.go | 4 ++-- p2p/v030/v030handshake_test.go | 4 ++-- p2p/v200/v200handshake_test.go | 4 ++-- rpc/grpcserver_test.go | 13 ++++++------- state/statebuffer_test.go | 14 +++++++------- state/statedb.go | 2 +- tools/genesisdump/main.go | 4 ++-- types/account.go | 9 ++++----- types/genesis.go | 6 +++--- types/p2p_test.go | 9 ++++----- 25 files changed, 91 insertions(+), 88 deletions(-) create mode 100644 internal/enc/hex.go diff --git a/account/key/crypto/v1strategy.go b/account/key/crypto/v1strategy.go index 6e6c2d9e4..8b3203e7d 100644 --- a/account/key/crypto/v1strategy.go +++ b/account/key/crypto/v1strategy.go @@ -10,12 +10,12 @@ import ( "crypto/cipher" "crypto/rand" "crypto/sha256" - "encoding/hex" "encoding/json" "errors" "io" "reflect" + "github.com/aergoio/aergo/v2/internal/enc" "github.com/aergoio/aergo/v2/types" "github.com/btcsuite/btcd/btcec" "golang.org/x/crypto/scrypt" @@ -105,9 +105,9 @@ func (ks *v1Strategy) Encrypt(key *PrivateKey, passphrase string) ([]byte, error cipher := v1CipherJSON{ Algorithm: cipherAlgorithm, Params: v1CipherParamsJSON{ - Iv: hex.EncodeToString(iv), + Iv: enc.HexEncode(iv), }, - Ciphertext: hex.EncodeToString(ciphertext), + Ciphertext: enc.HexEncode(ciphertext), } // json: kdf kdf := v1KdfJson{ @@ -117,9 +117,9 @@ func (ks *v1Strategy) Encrypt(key *PrivateKey, passphrase string) ([]byte, error N: scryptN, P: scryptP, R: scryptR, - Salt: hex.EncodeToString(salt), + Salt: enc.HexEncode(salt), }, - Mac: hex.EncodeToString(mac), + Mac: enc.HexEncode(mac), } rawAddress := GenerateAddress(&(key.ToECDSA().PublicKey)) encodedAddress := types.EncodeAddress(rawAddress) @@ -155,11 +155,11 @@ func (ks *v1Strategy) Decrypt(encrypted []byte, passphrase string) (*PrivateKey, } // check mac - mac, err := hex.DecodeString(kdf.Mac) + mac, err := enc.HexDecode(kdf.Mac) if nil != err { return nil, err } - cipherText, err := hex.DecodeString(cipher.Ciphertext) + cipherText, err := enc.HexDecode(cipher.Ciphertext) if nil != err { return nil, err } @@ -170,7 +170,7 @@ func (ks *v1Strategy) Decrypt(encrypted []byte, passphrase string) (*PrivateKey, // decrypt decryptKey := derivedKey[:16] - iv, err := hex.DecodeString(cipher.Params.Iv) + iv, err := enc.HexDecode(cipher.Params.Iv) if nil != err { return nil, err } @@ -207,7 +207,7 @@ func checkKeyFormat(keyFormat *v1KeyStoreFormat) error { } func deriveCipherKey(passphrase []byte, kdf v1KdfJson) ([]byte, error) { - salt, err := hex.DecodeString(kdf.Params.Salt) + salt, err := enc.HexDecode(kdf.Params.Salt) if err != nil { return nil, err } diff --git a/cmd/aergocli/cmd/blockchain_test.go b/cmd/aergocli/cmd/blockchain_test.go index 5f271a310..c8cc03892 100644 --- a/cmd/aergocli/cmd/blockchain_test.go +++ b/cmd/aergocli/cmd/blockchain_test.go @@ -1,7 +1,6 @@ package cmd import ( - "encoding/hex" "testing" "github.com/aergoio/aergo/v2/cmd/aergocli/util/encoding/json" @@ -49,6 +48,6 @@ func TestBlockchainWithMock(t *testing.T) { t.Fatal(err) } testBlockHashByte, _ := enc.B58Decode(testBlockHashString) - assert.Equal(t, hex.EncodeToString(testBlockHashByte), result["Hash"]) + assert.Equal(t, enc.HexEncode(testBlockHashByte), result["Hash"]) assert.Equal(t, float64(1), result["Height"]) } diff --git a/cmd/aergocli/cmd/contract.go b/cmd/aergocli/cmd/contract.go index 7a76698a6..68fb90072 100644 --- a/cmd/aergocli/cmd/contract.go +++ b/cmd/aergocli/cmd/contract.go @@ -3,7 +3,6 @@ package cmd import ( "bytes" "context" - "encoding/hex" "encoding/json" "errors" "fmt" @@ -201,7 +200,7 @@ func runDeployCmd(cmd *cobra.Command, args []string) error { if isHexString(data) { // the data is expected to be copied from aergoscan view of // the transaction that deployed the contract - payload, err = hex.DecodeString(data) + payload, err = enc.HexDecode(data) } else { // the data is the output of aergoluac code, err = luacEncoding.DecodeCode(data) diff --git a/cmd/aergocli/util/base64ToHex.go b/cmd/aergocli/util/base64ToHex.go index 0df49c088..98d86196d 100644 --- a/cmd/aergocli/util/base64ToHex.go +++ b/cmd/aergocli/util/base64ToHex.go @@ -1,9 +1,9 @@ package util import ( - "encoding/hex" "encoding/json" + "github.com/aergoio/aergo/v2/internal/enc" "github.com/aergoio/aergo/v2/types" ) @@ -18,9 +18,9 @@ type InOutBlockchainStatus struct { func ConvHexBlockchainStatus(in *types.BlockchainStatus) string { out := &InOutBlockchainStatus{} - out.Hash = hex.EncodeToString(in.BestBlockHash) + out.Hash = enc.HexEncode(in.BestBlockHash) out.Height = in.BestHeight - out.ChainIdHash = hex.EncodeToString(in.BestChainIdHash) + out.ChainIdHash = enc.HexEncode(in.BestChainIdHash) jsonout, err := json.Marshal(out) if err != nil { return "" diff --git a/cmd/aergoluac/encoding/codeEncoding.go b/cmd/aergoluac/encoding/codeEncoding.go index d0a383b01..33c8a6e15 100644 --- a/cmd/aergoluac/encoding/codeEncoding.go +++ b/cmd/aergoluac/encoding/codeEncoding.go @@ -1,7 +1,6 @@ package encoding import ( - "encoding/hex" "errors" "fmt" @@ -11,7 +10,7 @@ import ( const CodeVersion = 0xC0 func EncodeCode(code []byte) string { - encoded, _ := enc.B58CheckEncode(fmt.Sprintf("%x", CodeVersion), hex.EncodeToString(code)) + encoded, _ := enc.B58CheckEncode(fmt.Sprintf("%x", CodeVersion), enc.HexEncode(code)) return encoded } @@ -20,7 +19,7 @@ func DecodeCode(encodedCode string) ([]byte, error) { if err != nil { return nil, err } - decodedBytes, err := hex.DecodeString(decodedString) + decodedBytes, err := enc.HexDecode(decodedString) if err != nil { return nil, err } diff --git a/contract/ethstorageproof.go b/contract/ethstorageproof.go index da50b9902..fde576689 100644 --- a/contract/ethstorageproof.go +++ b/contract/ethstorageproof.go @@ -3,10 +3,10 @@ package contract import ( "bytes" "encoding/binary" - "encoding/hex" "errors" "math" + "github.com/aergoio/aergo/v2/internal/enc" "golang.org/x/crypto/sha3" ) @@ -33,7 +33,7 @@ func verifyEthStorageProof(key []byte, value rlpObject, expectedHash []byte, pro if len(key) == 0 || value == nil || len(proof) == 0 { return false } - key = []byte(hex.EncodeToString(keccak256(key))) + key = []byte(enc.HexEncode(keccak256(key))) valueRlpEncoded := rlpEncode(value) ks := keyStream{bytes.NewBuffer(key)} for i, p := range proof { @@ -50,7 +50,7 @@ func verifyEthStorageProof(key []byte, value rlpObject, expectedHash []byte, pro if err != nil { return false } - sharedNibbles = append(sharedNibbles, []byte(hex.EncodeToString(n[0][1:]))...) + sharedNibbles = append(sharedNibbles, []byte(enc.HexEncode(n[0][1:]))...) if len(sharedNibbles) == 0 { return false } @@ -180,7 +180,7 @@ func keccak256(data ...[]byte) []byte { } func keccak256Hex(data ...[]byte) string { - return hex.EncodeToString(keccak256(data...)) + return enc.HexEncode(keccak256(data...)) } func decodeHpHeader(b byte) (bool, []byte, error) { diff --git a/contract/ethstorageproof_test.go b/contract/ethstorageproof_test.go index e87de30a7..b00e24919 100644 --- a/contract/ethstorageproof_test.go +++ b/contract/ethstorageproof_test.go @@ -2,10 +2,11 @@ package contract import ( "bytes" - "encoding/hex" "fmt" "reflect" "testing" + + "github.com/aergoio/aergo/v2/internal/enc" ) func TestVerify(t *testing.T) { @@ -205,14 +206,14 @@ func removeHexPrefix(s string) string { } func toBytes(s string) []byte { - n, _ := hex.DecodeString(removeHexPrefix(s)) + n, _ := enc.HexDecode(removeHexPrefix(s)) return n } func proofToBytes(proof []string) [][]byte { var r [][]byte for _, n := range proof { - d, err := hex.DecodeString(removeHexPrefix(n)) + d, err := enc.HexDecode(removeHexPrefix(n)) if err != nil { return [][]byte{} } diff --git a/contract/hook_dbg.go b/contract/hook_dbg.go index 72f6a05e0..d1ce0ae75 100644 --- a/contract/hook_dbg.go +++ b/contract/hook_dbg.go @@ -10,11 +10,11 @@ package contract import "C" import ( "container/list" - "encoding/hex" "errors" "fmt" "path/filepath" + "github.com/aergoio/aergo/v2/internal/enc" "github.com/aergoio/aergo/v2/types" ) @@ -43,7 +43,7 @@ func (ce *executor) setCountHook(limit C.int) { } func HexAddrToBase58Addr(contract_id_hex string) (string, error) { - byteContractID, err := hex.DecodeString(contract_id_hex) + byteContractID, err := enc.HexDecode(contract_id_hex) if err != nil { return "", err } @@ -66,7 +66,7 @@ func HexAddrOrPlainStrToHexAddr(d string) string { } func PlainStrToHexAddr(d string) string { - return hex.EncodeToString(StrHash(d)) + return enc.HexEncode(StrHash(d)) } func SetBreakPoint(contract_id_hex string, line uint64) error { diff --git a/contract/vm.go b/contract/vm.go index 3f44d2b7d..d4e74492f 100644 --- a/contract/vm.go +++ b/contract/vm.go @@ -22,7 +22,6 @@ import "C" import ( "bytes" "context" - "encoding/hex" "encoding/json" "errors" "fmt" @@ -1459,7 +1458,7 @@ func (ce *executor) vmLoadCode(id []byte) { if ce.ctx.blockInfo.ForkVersion >= 3 { chunkId = C.CString("@" + types.EncodeAddress(id)) } else { - chunkId = C.CString(hex.EncodeToString(id)) + chunkId = C.CString(enc.HexEncode(id)) } defer C.free(unsafe.Pointer(chunkId)) if cErrMsg := C.vm_loadbuff( diff --git a/contract/vm_callback.go b/contract/vm_callback.go index 55f65f43b..dd4b73fca 100644 --- a/contract/vm_callback.go +++ b/contract/vm_callback.go @@ -26,7 +26,6 @@ struct rlp_obj { import "C" import ( "bytes" - "encoding/hex" "errors" "fmt" "math/big" @@ -871,7 +870,7 @@ func luaCryptoSha256(L *LState, arg unsafe.Pointer, argLen C.int) (*C.char, *C.c if checkHexString(string(data)) { dataStr := data[2:] var err error - data, err = hex.DecodeString(string(dataStr)) + data, err = enc.HexDecode(string(dataStr)) if err != nil { return nil, C.CString("[Contract.LuaCryptoSha256] hex decoding error: " + err.Error()) } @@ -880,14 +879,14 @@ func luaCryptoSha256(L *LState, arg unsafe.Pointer, argLen C.int) (*C.char, *C.c h.Write(data) resultHash := h.Sum(nil) - return C.CString("0x" + hex.EncodeToString(resultHash)), nil + return C.CString("0x" + enc.HexEncode(resultHash)), nil } func decodeHex(hexStr string) ([]byte, error) { if checkHexString(hexStr) { hexStr = hexStr[2:] } - return hex.DecodeString(hexStr) + return enc.HexDecode(hexStr) } //export luaECVerify @@ -971,7 +970,7 @@ func luaCryptoToBytes(data unsafe.Pointer, dataLen C.int) ([]byte, bool) { isHex := checkHexString(string(b)) if isHex { var err error - d, err = hex.DecodeString(string(b[2:])) + d, err = enc.HexDecode(string(b[2:])) if err != nil { isHex = false } @@ -1023,7 +1022,7 @@ func luaCryptoKeccak256(data unsafe.Pointer, dataLen C.int) (unsafe.Pointer, int d, isHex := luaCryptoToBytes(data, dataLen) h := keccak256(d) if isHex { - hexb := []byte("0x" + hex.EncodeToString(h)) + hexb := []byte("0x" + enc.HexEncode(h)) return C.CBytes(hexb), len(hexb) } else { return C.CBytes(h), len(h) diff --git a/internal/enc/hex.go b/internal/enc/hex.go new file mode 100644 index 000000000..148a65a73 --- /dev/null +++ b/internal/enc/hex.go @@ -0,0 +1,11 @@ +package enc + +import "encoding/hex" + +func HexEncode(b []byte) string { + return hex.EncodeToString(b) +} + +func HexDecode(s string) ([]byte, error) { + return hex.DecodeString(s) +} diff --git a/p2p/const_test.go b/p2p/const_test.go index 3e582da0a..a0e6b7fb3 100644 --- a/p2p/const_test.go +++ b/p2p/const_test.go @@ -7,7 +7,6 @@ package p2p import ( "bytes" - "encoding/hex" "fmt" "testing" @@ -22,7 +21,7 @@ import ( // this file collect sample global constants used in unit test. I'm tired of creating less meaningful variables in each tests. -var dummyBlockHash, _ = hex.DecodeString("4f461d85e869ade8a0544f8313987c33a9c06534e50c4ad941498299579bd7ac") +var dummyBlockHash, _ = enc.HexDecode("4f461d85e869ade8a0544f8313987c33a9c06534e50c4ad941498299579bd7ac") var dummyBlockHeight uint64 = 100215 var dummyTxHash, _ = enc.B58Decode("4H4zAkAyRV253K5SNBJtBxqUgHEbZcXbWFFc6cmQHY45") diff --git a/p2p/p2putil/PKTest_test.go b/p2p/p2putil/PKTest_test.go index 8a7a17477..40946a69b 100644 --- a/p2p/p2putil/PKTest_test.go +++ b/p2p/p2putil/PKTest_test.go @@ -1,9 +1,9 @@ package p2putil import ( - "encoding/hex" "testing" + "github.com/aergoio/aergo/v2/internal/enc" "github.com/btcsuite/btcd/btcec" "github.com/libp2p/go-libp2p-core/crypto" ) @@ -26,15 +26,15 @@ func PrintLibP2PKey(priv crypto.Key, marshaled []byte, t *testing.T) { if err != nil { t.Errorf("Failed to get bytes: %v", err.Error()) } else { - t.Logf("BT/MAR %v", hex.EncodeToString(oldBytes)) - t.Logf("RAW %v", hex.EncodeToString(newBytes)) + t.Logf("BT/MAR %v", enc.HexEncode(oldBytes)) + t.Logf("RAW %v", enc.HexEncode(newBytes)) } } func PrintBTCPKey(priv *btcec.PrivateKey, t *testing.T) { oldBytes := priv.Serialize() - t.Logf("PRIV %v", hex.EncodeToString(oldBytes)) - t.Logf("PUBLIC %v", hex.EncodeToString(priv.PubKey().SerializeCompressed())) + t.Logf("PRIV %v", enc.HexEncode(oldBytes)) + t.Logf("PUBLIC %v", enc.HexEncode(priv.PubKey().SerializeCompressed())) } func TestLibs(t *testing.T) { diff --git a/p2p/p2putil/cryptoutil_test.go b/p2p/p2putil/cryptoutil_test.go index c09b3cc7d..7670620ca 100644 --- a/p2p/p2putil/cryptoutil_test.go +++ b/p2p/p2putil/cryptoutil_test.go @@ -2,9 +2,9 @@ package p2putil import ( "bytes" - "encoding/hex" "testing" + "github.com/aergoio/aergo/v2/internal/enc" "github.com/btcsuite/btcd/btcec" "github.com/libp2p/go-libp2p-core/crypto" ) @@ -27,11 +27,11 @@ func TestConvertPKToLibP2P(t *testing.T) { } raw, err := got.Raw() if !bytes.Equal(raw, btcPK.Serialize()) { - t.Errorf("ConvertPKToLibP2P() pk = %v, want %v", hex.EncodeToString(raw), hex.EncodeToString(btcPK.Serialize())) + t.Errorf("ConvertPKToLibP2P() pk = %v, want %v", enc.HexEncode(raw), enc.HexEncode(btcPK.Serialize())) } rev := ConvertPKToBTCEC(got) if !bytes.Equal(rev.Serialize(), btcPK.Serialize()) { - t.Errorf("ConvertPKToBTCEC() pk = %v, want %v", hex.EncodeToString(rev.Serialize()), hex.EncodeToString(btcPK.Serialize())) + t.Errorf("ConvertPKToBTCEC() pk = %v, want %v", enc.HexEncode(rev.Serialize()), enc.HexEncode(btcPK.Serialize())) } marshaled, err := crypto.MarshalPrivateKey(got) @@ -68,11 +68,11 @@ func TestConvertPubKeyToLibP2P(t *testing.T) { } raw, err := got.Raw() if !bytes.Equal(raw, pubKey.SerializeCompressed()) { - t.Errorf("ConvertPubToLibP2P() pk = %v, want %v", hex.EncodeToString(raw), hex.EncodeToString(pubKey.SerializeCompressed())) + t.Errorf("ConvertPubToLibP2P() pk = %v, want %v", enc.HexEncode(raw), enc.HexEncode(pubKey.SerializeCompressed())) } rev := ConvertPubKeyToBTCEC(got) if !bytes.Equal(rev.SerializeCompressed(), pubKey.SerializeCompressed()) { - t.Errorf("ConvertPubKeyToBTCEC() pk = %v, want %v", hex.EncodeToString(rev.SerializeCompressed()), hex.EncodeToString(pubKey.SerializeCompressed())) + t.Errorf("ConvertPubKeyToBTCEC() pk = %v, want %v", enc.HexEncode(rev.SerializeCompressed()), enc.HexEncode(pubKey.SerializeCompressed())) } }) } diff --git a/p2p/p2putil/protobuf_test.go b/p2p/p2putil/protobuf_test.go index fbf94a9b0..963d2b116 100644 --- a/p2p/p2putil/protobuf_test.go +++ b/p2p/p2putil/protobuf_test.go @@ -21,10 +21,10 @@ func Test_MarshalTxResp(t *testing.T) { dummyTx := &types.Tx{Hash: dummyTxHash, Body: &types.TxBody{Payload: []byte("It's a good day to die.")}} txMarshaled, _ := proto.Marshal(dummyTx) txSize := len(dummyTxHash) + 2 + len(txMarshaled) + 2 // hash+ field desc of hash + tx+field desc of tx - //fmt.Println("TX : ",hex.EncodeToString(txMarshaled)) + //fmt.Println("TX : ",enc.HexEncode(txMarshaled)) emptyMarshaled, _ := proto.Marshal(&types.GetTransactionsResponse{}) emptySize := len(emptyMarshaled) - //fmt.Println("EMPTY: ",hex.EncodeToString(emptyMarshaled)) + //fmt.Println("EMPTY: ",enc.HexEncode(emptyMarshaled)) //fmt.Printf("Size of All nil: %d , tx size: %d ",emptySize, txSize) tests := []struct { name string @@ -59,7 +59,7 @@ func Test_MarshalTxResp(t *testing.T) { if actualSize < cut { cut = actualSize } - //fmt.Println("ACTUAL: ",hex.EncodeToString(actual[:cut])) + //fmt.Println("ACTUAL: ",enc.HexEncode(actual[:cut])) assert.Equal(t, test.expectedSize, actualSize) diff --git a/p2p/transport/networktransport_test.go b/p2p/transport/networktransport_test.go index be2b8e1f1..98bf32edf 100644 --- a/p2p/transport/networktransport_test.go +++ b/p2p/transport/networktransport_test.go @@ -6,13 +6,13 @@ package transport import ( - "encoding/hex" "testing" "time" "github.com/aergoio/aergo-lib/log" "github.com/aergoio/aergo/v2/config" cfg "github.com/aergoio/aergo/v2/config" + "github.com/aergoio/aergo/v2/internal/enc" "github.com/aergoio/aergo/v2/message" "github.com/aergoio/aergo/v2/p2p/p2pcommon" "github.com/aergoio/aergo/v2/p2p/p2pkey" @@ -35,7 +35,7 @@ func init() { // TODO split this test into two... one is to attempt make connection and the other is test peermanager if same peerid is given // Ignoring test for now, for lack of abstraction on AergoPeer struct func IgnoredTestP2PServiceRunAddPeer(t *testing.T) { - var sampleBlockHash, _ = hex.DecodeString("4f461d85e869ade8a0544f8313987c33a9c06534e50c4ad941498299579bd7ac") + var sampleBlockHash, _ = enc.HexDecode("4f461d85e869ade8a0544f8313987c33a9c06534e50c4ad941498299579bd7ac") var sampleBlockHeight uint64 = 100215 ctrl := gomock.NewController(t) diff --git a/p2p/v030/v030handshake_test.go b/p2p/v030/v030handshake_test.go index fa1d02fae..b8aa23123 100644 --- a/p2p/v030/v030handshake_test.go +++ b/p2p/v030/v030handshake_test.go @@ -7,13 +7,13 @@ package v030 import ( "context" - "encoding/hex" "fmt" "reflect" "testing" "github.com/aergoio/aergo-lib/log" "github.com/aergoio/aergo/v2/config" + "github.com/aergoio/aergo/v2/internal/enc" "github.com/aergoio/aergo/v2/p2p/p2pcommon" "github.com/aergoio/aergo/v2/p2p/p2pkey" "github.com/aergoio/aergo/v2/p2p/p2pmock" @@ -30,7 +30,7 @@ var ( myChainID, newVerChainID, theirChainID *types.ChainID myChainBytes, newVerChainBytes, theirChainBytes []byte samplePeerID, _ = types.IDB58Decode("16Uiu2HAmFqptXPfcdaCdwipB2fhHATgKGVFVPehDAPZsDKSU7jRm") - dummyBlockHash, _ = hex.DecodeString("4f461d85e869ade8a0544f8313987c33a9c06534e50c4ad941498299579bd7ac") + dummyBlockHash, _ = enc.HexDecode("4f461d85e869ade8a0544f8313987c33a9c06534e50c4ad941498299579bd7ac") dummyBlockHeight uint64 = 100215 ) diff --git a/p2p/v200/v200handshake_test.go b/p2p/v200/v200handshake_test.go index 072195921..1d446c6d5 100644 --- a/p2p/v200/v200handshake_test.go +++ b/p2p/v200/v200handshake_test.go @@ -7,7 +7,6 @@ package v200 import ( "context" - "encoding/hex" "fmt" "net" "reflect" @@ -17,6 +16,7 @@ import ( "github.com/aergoio/aergo-lib/log" "github.com/aergoio/aergo/v2/config" + "github.com/aergoio/aergo/v2/internal/enc" "github.com/aergoio/aergo/v2/p2p/p2pcommon" "github.com/aergoio/aergo/v2/p2p/p2pkey" "github.com/aergoio/aergo/v2/p2p/p2pmock" @@ -35,7 +35,7 @@ var ( theirChainBytes []byte samplePeerID, _ = types.IDB58Decode("16Uiu2HAmFqptXPfcdaCdwipB2fhHATgKGVFVPehDAPZsDKSU7jRm") - dummyBlockHash, _ = hex.DecodeString("4f461d85e869ade8a0544f8313987c33a9c06534e50c4ad941498299579bd7ac") + dummyBlockHash, _ = enc.HexDecode("4f461d85e869ade8a0544f8313987c33a9c06534e50c4ad941498299579bd7ac") dummyBlockID = types.MustParseBlockID(dummyBlockHash) dummyBlockHeight uint64 = 100215 diff --git a/rpc/grpcserver_test.go b/rpc/grpcserver_test.go index d58d129c6..e0a961de9 100644 --- a/rpc/grpcserver_test.go +++ b/rpc/grpcserver_test.go @@ -6,7 +6,6 @@ package rpc import ( "context" - "encoding/hex" "fmt" "math/big" "reflect" @@ -25,33 +24,33 @@ import ( func TestAergoRPCService_dummys(t *testing.T) { fmt.Println("dummyBlockHash") - fmt.Printf("HEX : %s \n", hex.EncodeToString(dummyBlockHash)) + fmt.Printf("HEX : %s \n", enc.HexEncode(dummyBlockHash)) fmt.Printf("B64 : %s \n", enc.B64Encode(dummyBlockHash)) fmt.Printf("B58 : %s \n", enc.B58Encode(dummyBlockHash)) fmt.Println() fmt.Println("dummyTx") - fmt.Printf("HEX : %s \n", hex.EncodeToString(dummyTxHash)) + fmt.Printf("HEX : %s \n", enc.HexEncode(dummyTxHash)) fmt.Printf("B64 : %s \n", enc.B64Encode(dummyTxHash)) fmt.Printf("B58 : %s \n", enc.B58Encode(dummyTxHash)) fmt.Println() fmt.Println("Address1") - fmt.Printf("HEX : %s \n", hex.EncodeToString(dummyWalletAddress)) + fmt.Printf("HEX : %s \n", enc.HexEncode(dummyWalletAddress)) fmt.Printf("B64 : %s \n", enc.B64Encode(dummyWalletAddress)) fmt.Printf("B58 : %s \n", enc.B58Encode(dummyWalletAddress)) fmt.Println() fmt.Println("Address2") - fmt.Printf("HEX : %s \n", hex.EncodeToString(dummyWalletAddress2)) + fmt.Printf("HEX : %s \n", enc.HexEncode(dummyWalletAddress2)) fmt.Printf("B64 : %s \n", enc.B64Encode(dummyWalletAddress2)) fmt.Printf("B58 : %s \n", enc.B58Encode(dummyWalletAddress2)) fmt.Println() } -var dummyBlockHash, _ = hex.DecodeString("4f461d85e869ade8a0544f8313987c33a9c06534e50c4ad941498299579bd7ac") +var dummyBlockHash, _ = enc.HexDecode("4f461d85e869ade8a0544f8313987c33a9c06534e50c4ad941498299579bd7ac") var dummyBlockHeight uint32 = 100215 -var dummyTxHash, _ = hex.DecodeString("218bdab4e87fb332b55eb89854ef553f9e3d440c81fff4161b672adede1261ee") +var dummyTxHash, _ = enc.HexDecode("218bdab4e87fb332b55eb89854ef553f9e3d440c81fff4161b672adede1261ee") // base64 encoding of dummyTxHash is "" var dummyWalletAddress, _ = enc.B58Decode("1Ee8uhLFXzkSRRU1orBpgXFAPpVi64aSYo") diff --git a/state/statebuffer_test.go b/state/statebuffer_test.go index 4f881eb60..ceb9c6ea5 100644 --- a/state/statebuffer_test.go +++ b/state/statebuffer_test.go @@ -1,9 +1,9 @@ package state import ( - "encoding/hex" "testing" + "github.com/aergoio/aergo/v2/internal/enc" "github.com/aergoio/aergo/v2/types" "github.com/stretchr/testify/assert" ) @@ -26,7 +26,7 @@ func TestBufferIndexStack(t *testing.T) { idxs.push(k0, 4) idxs.push(k1, 5) for i, v := range kset { - t.Logf("(%d)[%v]%v", i, hex.EncodeToString(v[:]), idxs[v]) + t.Logf("(%d)[%v]%v", i, enc.HexEncode(v[:]), idxs[v]) } assert.Equal(t, 4, idxs.pop(k0)) @@ -39,13 +39,13 @@ func TestBufferIndexStack(t *testing.T) { assert.Equal(t, 2, idxs.peek(k1)) assert.Equal(t, 2, idxs.pop(k1)) for i, v := range kset { - t.Logf("(%d)[%v]%v", i, hex.EncodeToString(v[:]), idxs[v]) + t.Logf("(%d)[%v]%v", i, enc.HexEncode(v[:]), idxs[v]) } idxs.push(k0, 6, 8, 12) idxs.push(k1, 7, 9, 10, 11) for i, v := range kset { - t.Logf("(%d)[%v]%v", i, hex.EncodeToString(v[:]), idxs[v]) + t.Logf("(%d)[%v]%v", i, enc.HexEncode(v[:]), idxs[v]) } assert.Equal(t, 12, idxs[k0].peek()) @@ -57,7 +57,7 @@ func TestBufferIndexRollback(t *testing.T) { idxs.push(k0, 0, 1, 3, 4, 6, 7, 8) idxs.push(k1, 2, 5, 9) for i, v := range kset { - t.Logf("(%d)[%v]%v", i, hex.EncodeToString(v[:]), idxs[v]) + t.Logf("(%d)[%v]%v", i, enc.HexEncode(v[:]), idxs[v]) } assert.Equal(t, 8, idxs[k0].peek()) @@ -65,7 +65,7 @@ func TestBufferIndexRollback(t *testing.T) { idxs.rollback(5) for i, v := range kset { - t.Logf("(%d)[%v]%v", i, hex.EncodeToString(v[:]), idxs[v]) + t.Logf("(%d)[%v]%v", i, enc.HexEncode(v[:]), idxs[v]) } assert.Equal(t, 4, idxs[k0].peek()) @@ -73,7 +73,7 @@ func TestBufferIndexRollback(t *testing.T) { idxs.rollback(0) for i, v := range kset { - t.Logf("(%d)[%v]%v", i, hex.EncodeToString(v[:]), idxs[v]) + t.Logf("(%d)[%v]%v", i, enc.HexEncode(v[:]), idxs[v]) } assert.Equal(t, -1, idxs[k0].peek()) diff --git a/state/statedb.go b/state/statedb.go index e77799613..213e1a007 100644 --- a/state/statedb.go +++ b/state/statedb.go @@ -553,7 +553,7 @@ func (states *StateDB) HasMarker(root []byte) bool { } marker := states.store.Get(common.Hasher(root)) if marker != nil && bytes.Equal(marker, stateMarker) { - // logger.Debug().Str("stateRoot", enc.ToString(root)).Str("marker", hex.EncodeToString(marker)).Msg("IsMarked") + // logger.Debug().Str("stateRoot", enc.ToString(root)).Str("marker", enc.HexEncode(marker)).Msg("IsMarked") return true } return false diff --git a/tools/genesisdump/main.go b/tools/genesisdump/main.go index 26de7d6ee..cecbb5f78 100644 --- a/tools/genesisdump/main.go +++ b/tools/genesisdump/main.go @@ -1,11 +1,11 @@ package main import ( - "encoding/hex" "encoding/json" "fmt" "os" + "github.com/aergoio/aergo/v2/internal/enc" "github.com/aergoio/aergo/v2/types" ) @@ -41,6 +41,6 @@ func main() { panic(err) } - str := "\"" + hex.EncodeToString(bs) + "\"" + str := "\"" + enc.HexEncode(bs) + "\"" fmt.Println(str) } diff --git a/types/account.go b/types/account.go index 550d993e5..2c86e8825 100644 --- a/types/account.go +++ b/types/account.go @@ -1,7 +1,6 @@ package types import ( - "encoding/hex" "errors" "fmt" "strings" @@ -50,7 +49,7 @@ func EncodeAddress(addr Address) string { if len(addr) != AddressLength { return string(addr) } - encoded, _ := enc.B58CheckEncode(fmt.Sprintf("%x", AddressVersion), hex.EncodeToString(addr)) + encoded, _ := enc.B58CheckEncode(fmt.Sprintf("%x", AddressVersion), enc.HexEncode(addr)) return encoded } @@ -72,7 +71,7 @@ func DecodeAddress(encodedAddr string) (Address, error) { if err != nil { return nil, err } - decodedBytes, err := hex.DecodeString(decodedString) + decodedBytes, err := enc.HexDecode(decodedString) if err != nil { return nil, err } @@ -95,7 +94,7 @@ func DecodeAddressBytes(decodedBytes []byte) (Address, error) { } func EncodePrivKey(key []byte) string { - encoded, _ := enc.B58CheckEncode(fmt.Sprintf("%x", PrivKeyVersion), hex.EncodeToString(key)) + encoded, _ := enc.B58CheckEncode(fmt.Sprintf("%x", PrivKeyVersion), enc.HexEncode(key)) return encoded } @@ -104,7 +103,7 @@ func DecodePrivKey(encodedKey string) ([]byte, error) { if err != nil { return nil, err } - decodedBytes, err := hex.DecodeString(decodedString) + decodedBytes, err := enc.HexDecode(decodedString) if err != nil { return nil, err } diff --git a/types/genesis.go b/types/genesis.go index 4ec01695f..4efe500ad 100644 --- a/types/genesis.go +++ b/types/genesis.go @@ -3,7 +3,6 @@ package types import ( "bytes" "encoding/binary" - "encoding/hex" "encoding/json" "fmt" "math" @@ -12,6 +11,7 @@ import ( "time" "github.com/aergoio/aergo/v2/internal/common" + "github.com/aergoio/aergo/v2/internal/enc" ) const ( @@ -333,7 +333,7 @@ func GetDefaultGenesis() *Genesis { } func GetMainNetGenesis() *Genesis { - if bs, err := hex.DecodeString(MainNetGenesis); err == nil { + if bs, err := enc.HexDecode(MainNetGenesis); err == nil { var g Genesis if err := json.Unmarshal(bs, &g); err == nil { return &g @@ -342,7 +342,7 @@ func GetMainNetGenesis() *Genesis { return nil } func GetTestNetGenesis() *Genesis { - if bs, err := hex.DecodeString(TestNetGenesis); err == nil { + if bs, err := enc.HexDecode(TestNetGenesis); err == nil { var g Genesis if err := json.Unmarshal(bs, &g); err == nil { return &g diff --git a/types/p2p_test.go b/types/p2p_test.go index d935b1942..4683e102e 100644 --- a/types/p2p_test.go +++ b/types/p2p_test.go @@ -6,7 +6,6 @@ package types import ( - "encoding/hex" "fmt" "testing" @@ -17,7 +16,7 @@ import ( func TestUnmarshalSize(t *testing.T) { var dummyTxHash, _ = enc.B58Decode("4H4zAkAyRV253K5SNBJtBxqUgHEbZcXbWFFc6cmQHY45") - fmt.Println("Hash: ", hex.EncodeToString(dummyTxHash)) + fmt.Println("Hash: ", enc.HexEncode(dummyTxHash)) sample := &NewTransactionsNotice{} @@ -35,7 +34,7 @@ func TestUnmarshalSize(t *testing.T) { actual, err = proto.Marshal(sample) assert.Nil(t, err) fmt.Println("Single hash notice size ", len(actual)) - fmt.Println("Hex: ", hex.EncodeToString(actual)) + fmt.Println("Hex: ", enc.HexEncode(actual)) assert.Equal(t, expectedLen, len(actual)) // 100 hashes @@ -48,7 +47,7 @@ func TestUnmarshalSize(t *testing.T) { actual, err = proto.Marshal(sample) assert.Nil(t, err) fmt.Println("Hundred hashes notice size ", len(actual)) - fmt.Println("Hex: ", hex.EncodeToString(actual[0:40])) + fmt.Println("Hex: ", enc.HexEncode(actual[0:40])) assert.Equal(t, expectedLen, len(actual)) // 1000 hashes @@ -61,7 +60,7 @@ func TestUnmarshalSize(t *testing.T) { actual, err = proto.Marshal(sample) assert.Nil(t, err) fmt.Println("Thousand hashes notice size ", len(actual)) - fmt.Println("Hex: ", hex.EncodeToString(actual[0:40])) + fmt.Println("Hex: ", enc.HexEncode(actual[0:40])) assert.Equal(t, expectedLen, len(actual)) } From 14d88329b0102f7b5c7888779357ae02e048e98b Mon Sep 17 00:00:00 2001 From: kch Date: Fri, 3 Nov 2023 06:15:15 +0000 Subject: [PATCH 3/6] add base64check test --- internal/enc/base58check_test.go | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 internal/enc/base58check_test.go diff --git a/internal/enc/base58check_test.go b/internal/enc/base58check_test.go new file mode 100644 index 000000000..e00d762f8 --- /dev/null +++ b/internal/enc/base58check_test.go @@ -0,0 +1,30 @@ +package enc + +import ( + "testing" + + "github.com/stretchr/testify/require" +) + +func TestB58CheckEncode(t *testing.T) { + for _, test := range []struct { + name string + version string + data string + expect string + }{ + {"T1", HexEncode([]byte{0}), HexEncode([]byte("Hello")), "1vSxRbq6DSYXc"}, + {"T2", HexEncode([]byte{1}), HexEncode([]byte("Hello")), "5BShidwAu2ieX"}, + {"T3", HexEncode([]byte{5}), HexEncode([]byte("abcdefghijklmnopqrstuvwxyz1234567890")), "2BSSzM1LQHgVeyiCPn5bEfgWY3HmiC3cbjGYFhTs1bVv5GTT7nJ8ajSE"}, + } { + t.Run(test.name, func(t *testing.T) { + got, err := B58CheckEncode(test.version, test.data) + require.NoErrorf(t, err, "B58CheckEncode() error = %v", err) + require.Equalf(t, test.expect, got, "B58CheckEncode() = %v, want %v", got, test.expect) + + recover, err := B58CheckDecode(got) + require.NoErrorf(t, err, "B58CheckDecode() error = %v", err) + require.Equalf(t, test.version+test.data, recover, "B58CheckDecode() = %v, want %v", recover, test.version+test.data) + }) + } +} From c6769095870fdf450c8cbadc0991ab10fddec223 Mon Sep 17 00:00:00 2001 From: kch Date: Sun, 5 Nov 2023 06:03:54 +0000 Subject: [PATCH 4/6] move gob common to enc --- chain/chaindb.go | 6 +++--- chain/chaindbForRaft.go | 8 ++++---- chain/recover.go | 3 +-- consensus/impl/dpos/bp/cluster.go | 4 ++-- consensus/impl/dpos/lib.go | 6 +++--- consensus/raftCommon.go | 3 +-- internal/common/bytes.go | 19 ------------------- internal/common/bytes_test.go | 22 ---------------------- internal/enc/base58.go | 9 ++++++++- internal/enc/base58check.go | 10 ++++++++++ internal/enc/base64.go | 6 ++++++ internal/enc/gob.go | 22 ++++++++++++++++++++++ internal/enc/gob_test.go | 23 +++++++++++++++++++++++ state/statedata.go | 6 +++--- types/genesis.go | 5 ++--- 15 files changed, 88 insertions(+), 64 deletions(-) create mode 100644 internal/enc/gob.go create mode 100644 internal/enc/gob_test.go diff --git a/chain/chaindb.go b/chain/chaindb.go index 6c8823bfa..b4d221e8e 100644 --- a/chain/chaindb.go +++ b/chain/chaindb.go @@ -651,7 +651,7 @@ func (cdb *ChainDB) getReceipts(blockHash []byte, blockNo types.BlockNo, var receipts types.Receipts receipts.SetHardFork(hardForkConfig, blockNo) - err := common.GobDecode(data, &receipts) + err := enc.GobDecode(data, &receipts) return &receipts, err } @@ -694,7 +694,7 @@ func (cdb *ChainDB) writeReceipts(blockHash []byte, blockNo types.BlockNo, recei dbTx := cdb.store.NewTx() defer dbTx.Discard() - val, _ := common.GobEncode(receipts) + val, _ := enc.GobEncode(receipts) dbTx.Set(dbkey.Receipts(blockHash, blockNo), val) dbTx.Commit() @@ -736,7 +736,7 @@ func (cdb *ChainDB) getReorgMarker() (*ReorgMarker, error) { } var marker ReorgMarker - err := common.GobDecode(data, &marker) + err := enc.GobDecode(data, &marker) return &marker, err } diff --git a/chain/chaindbForRaft.go b/chain/chaindbForRaft.go index 21b0da75e..c61495425 100644 --- a/chain/chaindbForRaft.go +++ b/chain/chaindbForRaft.go @@ -5,7 +5,7 @@ import ( "github.com/aergoio/aergo-lib/db" "github.com/aergoio/aergo/v2/consensus" - "github.com/aergoio/aergo/v2/internal/common" + "github.com/aergoio/aergo/v2/internal/enc" "github.com/aergoio/aergo/v2/types" "github.com/aergoio/aergo/v2/types/dbkey" "github.com/aergoio/etcd/raft/raftpb" @@ -234,7 +234,7 @@ func (cdb *ChainDB) GetRaftEntry(idx uint64) (*consensus.WalEntry, error) { } var entry consensus.WalEntry - if err := common.GobDecode(data, &entry); err != nil { + if err := enc.GobDecode(data, &entry); err != nil { return nil, err } @@ -421,7 +421,7 @@ func (cdb *ChainDB) WriteIdentity(identity *consensus.RaftIdentity) error { logger.Info().Str("id", identity.ToString()).Msg("save raft identity") - enc, err := common.GobEncode(identity) + enc, err := enc.GobEncode(identity) if err != nil { return ErrEncodeRaftIdentity } @@ -439,7 +439,7 @@ func (cdb *ChainDB) GetIdentity() (*consensus.RaftIdentity, error) { } var id consensus.RaftIdentity - if err := common.GobDecode(data, &id); err != nil { + if err := enc.GobDecode(data, &id); err != nil { return nil, ErrDecodeRaftIdentity } diff --git a/chain/recover.go b/chain/recover.go index 63a99bdc1..51e736a14 100644 --- a/chain/recover.go +++ b/chain/recover.go @@ -8,7 +8,6 @@ import ( "runtime" "runtime/debug" - "github.com/aergoio/aergo/v2/internal/common" "github.com/aergoio/aergo/v2/internal/enc" "github.com/aergoio/aergo/v2/types" "github.com/aergoio/aergo/v2/types/dbkey" @@ -218,7 +217,7 @@ func (rm *ReorgMarker) delete() { } func (rm *ReorgMarker) toBytes() ([]byte, error) { - return common.GobEncode(rm) + return enc.GobEncode(rm) } func (rm *ReorgMarker) toString() string { diff --git a/consensus/impl/dpos/bp/cluster.go b/consensus/impl/dpos/bp/cluster.go index 00447e060..060671299 100644 --- a/consensus/impl/dpos/bp/cluster.go +++ b/consensus/impl/dpos/bp/cluster.go @@ -16,7 +16,7 @@ import ( "github.com/aergoio/aergo-lib/log" "github.com/aergoio/aergo/v2/consensus" "github.com/aergoio/aergo/v2/contract/system" - "github.com/aergoio/aergo/v2/internal/common" + "github.com/aergoio/aergo/v2/internal/enc" "github.com/aergoio/aergo/v2/state" "github.com/aergoio/aergo/v2/types" "github.com/davecgh/go-spew/spew" @@ -287,7 +287,7 @@ func buildKey(blockNo types.BlockNo) []byte { // Value returns s.list. func (s *Snapshot) Value() []byte { - b, err := common.GobEncode(s.List) + b, err := enc.GobEncode(s.List) if err != nil { logger.Debug().Err(err).Msg("BP list encoding failed") return nil diff --git a/consensus/impl/dpos/lib.go b/consensus/impl/dpos/lib.go index a9a675e5d..41660aa89 100644 --- a/consensus/impl/dpos/lib.go +++ b/consensus/impl/dpos/lib.go @@ -7,7 +7,7 @@ import ( "github.com/aergoio/aergo-lib/db" "github.com/aergoio/aergo/v2/consensus" - "github.com/aergoio/aergo/v2/internal/common" + "github.com/aergoio/aergo/v2/internal/enc" "github.com/aergoio/aergo/v2/p2p/p2pkey" "github.com/aergoio/aergo/v2/types" "github.com/aergoio/aergo/v2/types/dbkey" @@ -235,7 +235,7 @@ func (ls *libStatus) load(endBlockNo types.BlockNo) { } func (ls *libStatus) save(tx consensus.TxWriter) error { - b, err := common.GobEncode(ls) + b, err := enc.GobEncode(ls) if err != nil { return err } @@ -397,7 +397,7 @@ func (bs *bootLoader) decodeStatus(key []byte, dst interface{}) error { return fmt.Errorf("LIB status not found: key = %v", string(key)) } - err := common.GobDecode(value, dst) + err := enc.GobDecode(value, dst) if err != nil { logger.Panic().Err(err).Str("key", string(key)). Msg("failed to decode DPoS status") diff --git a/consensus/raftCommon.go b/consensus/raftCommon.go index c4b96d63e..30216420b 100644 --- a/consensus/raftCommon.go +++ b/consensus/raftCommon.go @@ -10,7 +10,6 @@ import ( "fmt" "io" - "github.com/aergoio/aergo/v2/internal/common" "github.com/aergoio/aergo/v2/internal/enc" "github.com/aergoio/aergo/v2/types" "github.com/aergoio/etcd/raft" @@ -59,7 +58,7 @@ type WalEntry struct { } func (we *WalEntry) ToBytes() ([]byte, error) { - return common.GobEncode(we) + return enc.GobEncode(we) } func (we *WalEntry) ToString() string { diff --git a/internal/common/bytes.go b/internal/common/bytes.go index 93db56386..02cd2a0f9 100644 --- a/internal/common/bytes.go +++ b/internal/common/bytes.go @@ -1,10 +1,5 @@ package common -import ( - "bytes" - "encoding/gob" -) - // IsZero returns true if argument is empty or zero func IsZero(argv []byte) bool { if len(argv) == 0 { @@ -25,17 +20,3 @@ func Compactz(argv []byte) []byte { } return argv } - -// GobEncode encodes e by using gob and returns. -func GobEncode(e interface{}) ([]byte, error) { - var buf bytes.Buffer - err := gob.NewEncoder(&buf).Encode(e) - - return buf.Bytes(), err -} - -// GobDecode decodes a gob-encoded value v. -func GobDecode(v []byte, e interface{}) error { - dec := gob.NewDecoder(bytes.NewBuffer(v)) - return dec.Decode(e) -} diff --git a/internal/common/bytes_test.go b/internal/common/bytes_test.go index 0a669c416..805d0c79a 100644 --- a/internal/common/bytes_test.go +++ b/internal/common/bytes_test.go @@ -1,23 +1 @@ package common - -import ( - "testing" - - "github.com/stretchr/testify/assert" -) - -func TestGobCodec(t *testing.T) { - a := assert.New(t) - - x := []int{1, 2, 3} - b, err := GobEncode(x) - a.Nil(err) - - y := []int{0, 0, 0} - err = GobDecode(b, &y) - a.Nil(err) - - for i, v := range x { - a.Equal(v, y[i]) - } -} diff --git a/internal/enc/base58.go b/internal/enc/base58.go index 363cf5d6a..bf28f3ce5 100644 --- a/internal/enc/base58.go +++ b/internal/enc/base58.go @@ -1,6 +1,8 @@ package enc -import "github.com/mr-tron/base58/base58" +import ( + "github.com/mr-tron/base58/base58" +) // B58Encode returns human-readable (base58) string from b. Calling with empty or nil slice returns empty string. func B58Encode(b []byte) string { @@ -11,3 +13,8 @@ func B58Encode(b []byte) string { func B58Decode(s string) ([]byte, error) { return base58.Decode(s) } + +func B58DecodeOrNil(s string) []byte { + buf, _ := B58Decode(s) + return buf +} diff --git a/internal/enc/base58check.go b/internal/enc/base58check.go index 723329e38..24bed42b4 100644 --- a/internal/enc/base58check.go +++ b/internal/enc/base58check.go @@ -8,6 +8,16 @@ func B58CheckEncode(version string, data string) (string, error) { return base58check.Encode(version, data) } +func B58CheckEncodeOrNil(version string, data string) string { + buf, _ := B58CheckEncode(version, data) + return buf +} + func B58CheckDecode(encoded string) (string, error) { return base58check.Decode(encoded) } + +func B58CheckDecodeOrNil(encoded string) string { + buf, _ := B58CheckDecode(encoded) + return buf +} diff --git a/internal/enc/base64.go b/internal/enc/base64.go index bc755ebd3..da27e7bed 100644 --- a/internal/enc/base64.go +++ b/internal/enc/base64.go @@ -9,3 +9,9 @@ func B64Encode(s []byte) string { func B64Decode(s string) ([]byte, error) { return base64.StdEncoding.DecodeString(s) } + +// Do not use processing real data, Only use for Logging or Testing. +func B64DecodeOrNil(s string) []byte { + buf, _ := B64Decode(s) + return buf +} diff --git a/internal/enc/gob.go b/internal/enc/gob.go new file mode 100644 index 000000000..def0e8bf0 --- /dev/null +++ b/internal/enc/gob.go @@ -0,0 +1,22 @@ +package enc + +import ( + "bytes" + "encoding/gob" +) + +// GobEncode encodes e by using gob and returns. +func GobEncode(e interface{}) ([]byte, error) { + var buf bytes.Buffer + err := gob.NewEncoder(&buf).Encode(e) + if err != nil { + return nil, err + } + return buf.Bytes(), nil +} + +// GobDecode decodes a gob-encoded value v. +func GobDecode(v []byte, e interface{}) error { + dec := gob.NewDecoder(bytes.NewBuffer(v)) + return dec.Decode(e) +} diff --git a/internal/enc/gob_test.go b/internal/enc/gob_test.go new file mode 100644 index 000000000..cfa215281 --- /dev/null +++ b/internal/enc/gob_test.go @@ -0,0 +1,23 @@ +package enc + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestGobCodec(t *testing.T) { + a := assert.New(t) + + x := []int{1, 2, 3} + b, err := GobEncode(x) + a.Nil(err) + + y := []int{0, 0, 0} + err = GobDecode(b, &y) + a.Nil(err) + + for i, v := range x { + a.Equal(v, y[i]) + } +} diff --git a/state/statedata.go b/state/statedata.go index 7cbe94260..1f727bda5 100644 --- a/state/statedata.go +++ b/state/statedata.go @@ -2,7 +2,7 @@ package state import ( "github.com/aergoio/aergo-lib/db" - "github.com/aergoio/aergo/v2/internal/common" + "github.com/aergoio/aergo/v2/internal/enc" "github.com/aergoio/aergo/v2/types" "github.com/golang/protobuf/proto" ) @@ -22,7 +22,7 @@ func saveData(store db.DB, key []byte, data interface{}) error { return err } default: - raw, err = common.GobEncode(data) + raw, err = enc.GobEncode(data) if err != nil { return err } @@ -47,7 +47,7 @@ func loadData(store db.DB, key []byte, data interface{}) error { case proto.Message: err = proto.Unmarshal(raw, data.(proto.Message)) default: - err = common.GobDecode(raw, data) + err = enc.GobDecode(raw, data) } return err } diff --git a/types/genesis.go b/types/genesis.go index 4efe500ad..aadf0ac9a 100644 --- a/types/genesis.go +++ b/types/genesis.go @@ -10,7 +10,6 @@ import ( "strings" "time" - "github.com/aergoio/aergo/v2/internal/common" "github.com/aergoio/aergo/v2/internal/enc" ) @@ -281,7 +280,7 @@ func (g *Genesis) ChainID() ([]byte, error) { func (g Genesis) Bytes() []byte { // Omit the Balance to reduce the resulting data size. g.Balance = nil - if b, err := common.GobEncode(g); err == nil { + if b, err := enc.GobEncode(g); err == nil { return b } return nil @@ -373,7 +372,7 @@ func GetTestGenesis() *Genesis { // GetGenesisFromBytes decodes & return Genesis from b. func GetGenesisFromBytes(b []byte) *Genesis { g := &Genesis{} - if err := common.GobDecode(b, g); err == nil { + if err := enc.GobDecode(b, g); err == nil { return g } return nil From c5fcd89154f96378729f1c3e019211eace50e808 Mon Sep 17 00:00:00 2001 From: kch Date: Mon, 6 Nov 2023 02:12:43 +0000 Subject: [PATCH 5/6] enc - split packages --- account/key/crypto/v1strategy.go | 18 +++---- chain/blockvalidator.go | 22 ++++----- chain/chainanchor.go | 6 +-- chain/chaindb.go | 21 ++++---- chain/chaindbForRaft.go | 8 ++-- chain/chainhandle.go | 14 +++--- chain/chainservice.go | 22 ++++----- chain/chainverifier.go | 8 ++-- chain/common.go | 4 +- chain/orphanpool.go | 4 +- chain/recover.go | 13 ++--- chain/reorg.go | 4 +- chain/signVerifier.go | 4 +- cmd/aergocli/cmd/blockchain_test.go | 9 ++-- cmd/aergocli/cmd/committx_test.go | 6 +-- cmd/aergocli/cmd/contract.go | 9 ++-- cmd/aergocli/cmd/enterprise.go | 4 +- cmd/aergocli/cmd/enterprise_test.go | 6 +-- cmd/aergocli/cmd/getblock.go | 4 +- cmd/aergocli/cmd/getstate.go | 4 +- cmd/aergocli/cmd/gettx.go | 4 +- cmd/aergocli/cmd/keygen.go | 4 +- cmd/aergocli/cmd/listblocks.go | 4 +- cmd/aergocli/cmd/receipt.go | 4 +- cmd/aergocli/cmd/sendtx.go | 4 +- cmd/aergocli/cmd/sendtx_test.go | 6 +-- cmd/aergocli/cmd/signtx.go | 4 +- cmd/aergocli/cmd/signtx_test.go | 4 +- cmd/aergocli/cmd/vote.go | 6 +-- cmd/aergocli/util/base58addr.go | 48 +++++++++---------- cmd/aergocli/util/base58addr_test.go | 12 ++--- cmd/aergocli/util/base64ToHex.go | 6 +-- cmd/aergocli/util/encoding/json/decode.go | 4 +- cmd/aergocli/util/encoding/json/encode.go | 4 +- cmd/aergoluac/encoding/codeEncoding.go | 9 ++-- cmd/aergosvr/init.go | 6 +-- cmd/colaris/cmd/current.go | 5 +- consensus/chain/block.go | 8 ++-- consensus/impl/dpos/blockfactory.go | 6 +-- consensus/impl/dpos/bp/cluster.go | 4 +- consensus/impl/dpos/lib.go | 6 +-- consensus/impl/dpos/lib_test.go | 6 +-- consensus/impl/raftv2/blockfactory.go | 4 +- consensus/impl/raftv2/cluster.go | 10 ++-- consensus/impl/sbp/sbp.go | 4 +- consensus/raftCommon.go | 7 +-- contract/contract_test.go | 46 +++++++++--------- contract/enterprise/validate.go | 4 +- contract/ethstorageproof.go | 8 ++-- contract/ethstorageproof_test.go | 6 +-- contract/hook_dbg.go | 6 +-- contract/statesql.go | 4 +- contract/system/execute.go | 4 +- contract/system/execute_test.go | 4 +- contract/system/vote.go | 8 ++-- contract/system/vote_test.go | 8 ++-- contract/system/voteresult.go | 14 +++--- contract/system/vprt.go | 8 ++-- contract/system/vprt_test.go | 6 +-- contract/vm.go | 11 +++-- contract/vm_callback.go | 17 +++---- contract/vm_direct/vm_direct.go | 10 ++-- contract/vm_dummy/vm_dummy.go | 4 +- internal/enc/base58.go | 20 -------- internal/enc/base58/base58.go | 20 ++++++++ internal/enc/{ => base58}/base58_test.go | 6 +-- internal/enc/base58check.go | 23 --------- internal/enc/base58check/base58check.go | 23 +++++++++ .../enc/{ => base58check}/base58check_test.go | 13 ++--- internal/enc/{ => base64}/base64.go | 10 ++-- internal/enc/{ => gob}/gob.go | 10 ++-- internal/enc/{ => gob}/gob_test.go | 6 +-- internal/enc/hex.go | 11 ----- internal/enc/hex/hex.go | 11 +++++ internal/merkle/merkle_test.go | 6 +-- mempool/mempool.go | 14 +++--- mempool/txverifier.go | 4 +- p2p/actorwork.go | 6 +-- p2p/const_test.go | 28 ++++++----- p2p/hashreceiver_test.go | 4 +- p2p/msgorder.go | 4 +- p2p/p2pkey/nodekey.go | 4 +- p2p/p2putil/PKTest_test.go | 10 ++-- p2p/p2putil/certificate_test.go | 8 ++-- p2p/p2putil/cryptoutil_test.go | 10 ++-- p2p/p2putil/protobuf_test.go | 10 ++-- p2p/p2putil/util.go | 6 +-- p2p/p2putil/util_test.go | 6 +-- p2p/subproto/block.go | 6 +-- p2p/subproto/blockhash_test.go | 6 +-- p2p/subproto/bp.go | 6 +-- p2p/subproto/bp_test.go | 4 +- p2p/subproto/getblock.go | 6 +-- p2p/subproto/getblock_test.go | 6 +-- p2p/subproto/ping_test.go | 4 +- p2p/subproto/raftstub.go | 4 +- p2p/subproto/tx.go | 4 +- p2p/subproto/tx_test.go | 4 +- p2p/synctx_test.go | 8 ++-- p2p/transport/networktransport_test.go | 4 +- p2p/txreceiver.go | 4 +- p2p/v030/v030handshake_test.go | 4 +- p2p/v030/v030io_test.go | 6 +-- p2p/v030/v032handshake.go | 4 +- p2p/v030/v033handshake.go | 4 +- p2p/v200/v200handshake.go | 4 +- p2p/v200/v200handshake_test.go | 4 +- rpc/grpcserver_test.go | 36 +++++++------- state/chainstatedb.go | 10 ++-- state/statebuffer_test.go | 14 +++--- state/statedata.go | 6 +-- state/statedb.go | 8 ++-- state/storage.go | 6 +-- syncer/blockfetcher.go | 26 +++++----- syncer/blockprocessor.go | 18 +++---- syncer/finder.go | 8 ++-- syncer/hashfetcher.go | 12 ++--- tools/genesisdump/main.go | 4 +- types/account.go | 15 +++--- types/blockchain.go | 8 ++-- types/common.go | 11 +++-- types/genesis.go | 11 +++-- types/genesis_test.go | 4 +- types/logging.go | 8 ++-- types/logging_test.go | 4 +- types/p2p_test.go | 13 ++--- types/p2plogging.go | 26 +++++----- types/receipt.go | 10 ++-- types/state.go | 4 +- types/transaction.go | 4 +- 130 files changed, 597 insertions(+), 581 deletions(-) delete mode 100644 internal/enc/base58.go create mode 100644 internal/enc/base58/base58.go rename internal/enc/{ => base58}/base58_test.go (90%) delete mode 100644 internal/enc/base58check.go create mode 100644 internal/enc/base58check/base58check.go rename internal/enc/{ => base58check}/base58check_test.go (56%) rename internal/enc/{ => base64}/base64.go (57%) rename internal/enc/{ => gob}/gob.go (53%) rename internal/enc/{ => gob}/gob_test.go (79%) delete mode 100644 internal/enc/hex.go create mode 100644 internal/enc/hex/hex.go diff --git a/account/key/crypto/v1strategy.go b/account/key/crypto/v1strategy.go index 8b3203e7d..d4a8a32ac 100644 --- a/account/key/crypto/v1strategy.go +++ b/account/key/crypto/v1strategy.go @@ -15,7 +15,7 @@ import ( "io" "reflect" - "github.com/aergoio/aergo/v2/internal/enc" + "github.com/aergoio/aergo/v2/internal/enc/hex" "github.com/aergoio/aergo/v2/types" "github.com/btcsuite/btcd/btcec" "golang.org/x/crypto/scrypt" @@ -105,9 +105,9 @@ func (ks *v1Strategy) Encrypt(key *PrivateKey, passphrase string) ([]byte, error cipher := v1CipherJSON{ Algorithm: cipherAlgorithm, Params: v1CipherParamsJSON{ - Iv: enc.HexEncode(iv), + Iv: hex.Encode(iv), }, - Ciphertext: enc.HexEncode(ciphertext), + Ciphertext: hex.Encode(ciphertext), } // json: kdf kdf := v1KdfJson{ @@ -117,9 +117,9 @@ func (ks *v1Strategy) Encrypt(key *PrivateKey, passphrase string) ([]byte, error N: scryptN, P: scryptP, R: scryptR, - Salt: enc.HexEncode(salt), + Salt: hex.Encode(salt), }, - Mac: enc.HexEncode(mac), + Mac: hex.Encode(mac), } rawAddress := GenerateAddress(&(key.ToECDSA().PublicKey)) encodedAddress := types.EncodeAddress(rawAddress) @@ -155,11 +155,11 @@ func (ks *v1Strategy) Decrypt(encrypted []byte, passphrase string) (*PrivateKey, } // check mac - mac, err := enc.HexDecode(kdf.Mac) + mac, err := hex.Decode(kdf.Mac) if nil != err { return nil, err } - cipherText, err := enc.HexDecode(cipher.Ciphertext) + cipherText, err := hex.Decode(cipher.Ciphertext) if nil != err { return nil, err } @@ -170,7 +170,7 @@ func (ks *v1Strategy) Decrypt(encrypted []byte, passphrase string) (*PrivateKey, // decrypt decryptKey := derivedKey[:16] - iv, err := enc.HexDecode(cipher.Params.Iv) + iv, err := hex.Decode(cipher.Params.Iv) if nil != err { return nil, err } @@ -207,7 +207,7 @@ func checkKeyFormat(keyFormat *v1KeyStoreFormat) error { } func deriveCipherKey(passphrase []byte, kdf v1KdfJson) ([]byte, error) { - salt, err := enc.HexDecode(kdf.Params.Salt) + salt, err := hex.Decode(kdf.Params.Salt) if err != nil { return nil, err } diff --git a/chain/blockvalidator.go b/chain/blockvalidator.go index 24c12add7..42c795042 100644 --- a/chain/blockvalidator.go +++ b/chain/blockvalidator.go @@ -10,7 +10,7 @@ import ( "errors" "fmt" - "github.com/aergoio/aergo/v2/internal/enc" + "github.com/aergoio/aergo/v2/internal/enc/base58" "github.com/aergoio/aergo/v2/pkg/component" "github.com/aergoio/aergo/v2/state" "github.com/aergoio/aergo/v2/types" @@ -90,7 +90,7 @@ func (t validateReport) toString() string { result = "failed" } - msgStr = fmt.Sprintf("%s : %s. block= %s, computed=%s", t.name, result, enc.B58Encode(t.src), enc.B58Encode(t.target)) + msgStr = fmt.Sprintf("%s : %s. block= %s, computed=%s", t.name, result, base58.Encode(t.src), base58.Encode(t.target)) return msgStr } @@ -99,7 +99,7 @@ func (bv *BlockValidator) ValidateBody(block *types.Block) error { txs := block.GetBody().GetTxs() // TxRootHash - logger.Debug().Int("Txlen", len(txs)).Str("TxRoot", enc.B58Encode(block.GetHeader().GetTxsRootHash())). + logger.Debug().Int("Txlen", len(txs)).Str("TxRoot", base58.Encode(block.GetHeader().GetTxsRootHash())). Msg("tx root verify") hdrRootHash := block.GetHeader().GetTxsRootHash() @@ -112,8 +112,8 @@ func (bv *BlockValidator) ValidateBody(block *types.Block) error { if !ret { logger.Error().Str("block", block.ID()). - Str("txroot", enc.B58Encode(hdrRootHash)). - Str("compute txroot", enc.B58Encode(computeTxRootHash)). + Str("txroot", base58.Encode(hdrRootHash)). + Str("compute txroot", base58.Encode(computeTxRootHash)). Msg("tx root validation failed") return ErrorBlockVerifyTxRoot @@ -160,13 +160,13 @@ func (bv *BlockValidator) ValidatePost(sdbRoot []byte, receipts *types.Receipts, } if !ret { logger.Error().Str("block", block.ID()). - Str("hdrroot", enc.B58Encode(hdrRoot)). - Str("sdbroot", enc.B58Encode(sdbRoot)). + Str("hdrroot", base58.Encode(hdrRoot)). + Str("sdbroot", base58.Encode(sdbRoot)). Msg("block root hash validation failed") return ErrorBlockVerifyStateRoot } - logger.Debug().Str("sdbroot", enc.B58Encode(sdbRoot)). + logger.Debug().Str("sdbroot", base58.Encode(sdbRoot)). Msg("block root hash validation succeed") hdrRoot = block.GetHeader().ReceiptsRootHash @@ -177,12 +177,12 @@ func (bv *BlockValidator) ValidatePost(sdbRoot []byte, receipts *types.Receipts, bv.report(validateReport{name: "Verify receipt merkle root", pass: ret, src: hdrRoot, target: receiptsRoot}) } else if !ret { logger.Error().Str("block", block.ID()). - Str("hdrroot", enc.B58Encode(hdrRoot)). - Str("receipts_root", enc.B58Encode(receiptsRoot)). + Str("hdrroot", base58.Encode(hdrRoot)). + Str("receipts_root", base58.Encode(receiptsRoot)). Msg("receipts root hash validation failed") return ErrorBlockVerifyReceiptRoot } - logger.Debug().Str("receipts_root", enc.B58Encode(receiptsRoot)). + logger.Debug().Str("receipts_root", base58.Encode(receiptsRoot)). Msg("receipt root hash validation succeed") return nil diff --git a/chain/chainanchor.go b/chain/chainanchor.go index 5cb88c71a..b252dfe23 100644 --- a/chain/chainanchor.go +++ b/chain/chainanchor.go @@ -6,7 +6,7 @@ package chain import ( - "github.com/aergoio/aergo/v2/internal/enc" + "github.com/aergoio/aergo/v2/internal/enc/base58" "github.com/aergoio/aergo/v2/types" ) @@ -72,7 +72,7 @@ func (cs *ChainService) getAnchorsFromHash(blockHash []byte) ChainAnchor { return nil } - logger.Debug().Uint64("no", latestNo).Str("hash", enc.B58Encode(blockHash)).Msg("anchor") + logger.Debug().Uint64("no", latestNo).Str("hash", base58.Encode(blockHash)).Msg("anchor") anchors = append(anchors, blockHash) if latestNo == 0 { @@ -91,7 +91,7 @@ func (cs *ChainService) getAnchorsFromHash(blockHash []byte) ChainAnchor { return nil } - logger.Debug().Uint64("no", latestNo).Str("hash", enc.B58Encode(blockHash)).Msg("anchor") + logger.Debug().Uint64("no", latestNo).Str("hash", base58.Encode(blockHash)).Msg("anchor") anchors = append(anchors, blockHash) if latestNo <= dec { diff --git a/chain/chaindb.go b/chain/chaindb.go index b4d221e8e..658a6a121 100644 --- a/chain/chaindb.go +++ b/chain/chaindb.go @@ -16,7 +16,8 @@ import ( "github.com/aergoio/aergo/v2/config" "github.com/aergoio/aergo/v2/consensus" "github.com/aergoio/aergo/v2/internal/common" - "github.com/aergoio/aergo/v2/internal/enc" + "github.com/aergoio/aergo/v2/internal/enc/base58" + "github.com/aergoio/aergo/v2/internal/enc/gob" "github.com/aergoio/aergo/v2/types" "github.com/aergoio/aergo/v2/types/dbkey" "github.com/golang/protobuf/proto" @@ -44,7 +45,7 @@ func (e ErrNoBlock) Error() string { switch id := e.id.(type) { case []byte: - idStr = fmt.Sprintf("blockHash=%v", enc.B58Encode(id)) + idStr = fmt.Sprintf("blockHash=%v", base58.Encode(id)) default: idStr = fmt.Sprintf("blockNo=%v", id) } @@ -444,7 +445,7 @@ func (cdb *ChainDB) addTxsOfBlock(dbTx *db.Transaction, txs []*types.Tx, blockHa for i, txEntry := range txs { if err := cdb.addTx(dbTx, txEntry, blockHash, i); err != nil { - logger.Error().Err(err).Str("hash", enc.B58Encode(blockHash)).Int("txidx", i). + logger.Error().Err(err).Str("hash", base58.Encode(blockHash)).Int("txidx", i). Msg("failed to add tx") return err @@ -610,7 +611,7 @@ func (cdb *ChainDB) getTx(txHash []byte) (*types.Tx, *types.TxIdx, error) { err := cdb.loadData(txHash, txIdx) if err != nil { - return nil, nil, fmt.Errorf("tx not found: txHash=%v", enc.B58Encode(txHash)) + return nil, nil, fmt.Errorf("tx not found: txHash=%v", base58.Encode(txHash)) } block, err := cdb.getBlock(txIdx.BlockHash) if err != nil { @@ -621,7 +622,7 @@ func (cdb *ChainDB) getTx(txHash []byte) (*types.Tx, *types.TxIdx, error) { return nil, nil, fmt.Errorf("wrong tx idx: %d", txIdx.Idx) } tx := txs[txIdx.Idx] - logger.Debug().Str("hash", enc.B58Encode(txHash)).Msg("getTx") + logger.Debug().Str("hash", base58.Encode(txHash)).Msg("getTx") return tx, txIdx, nil } @@ -651,7 +652,7 @@ func (cdb *ChainDB) getReceipts(blockHash []byte, blockNo types.BlockNo, var receipts types.Receipts receipts.SetHardFork(hardForkConfig, blockNo) - err := enc.GobDecode(data, &receipts) + err := gob.Decode(data, &receipts) return &receipts, err } @@ -679,9 +680,9 @@ func (cdb *ChainDB) GetChainTree() ([]byte, error) { hash, _ := cdb.getHashByNo(i) tree = append(tree, ChainInfo{ Height: i, - Hash: enc.B58Encode(hash), + Hash: base58.Encode(hash), }) - logger.Info().Str("hash", enc.B58Encode(hash)).Msg("GetChainTree") + logger.Info().Str("hash", base58.Encode(hash)).Msg("GetChainTree") } jsonBytes, err := json.Marshal(tree) if err != nil { @@ -694,7 +695,7 @@ func (cdb *ChainDB) writeReceipts(blockHash []byte, blockNo types.BlockNo, recei dbTx := cdb.store.NewTx() defer dbTx.Discard() - val, _ := enc.GobEncode(receipts) + val, _ := gob.Encode(receipts) dbTx.Set(dbkey.Receipts(blockHash, blockNo), val) dbTx.Commit() @@ -736,7 +737,7 @@ func (cdb *ChainDB) getReorgMarker() (*ReorgMarker, error) { } var marker ReorgMarker - err := enc.GobDecode(data, &marker) + err := gob.Decode(data, &marker) return &marker, err } diff --git a/chain/chaindbForRaft.go b/chain/chaindbForRaft.go index c61495425..14a754d54 100644 --- a/chain/chaindbForRaft.go +++ b/chain/chaindbForRaft.go @@ -5,7 +5,7 @@ import ( "github.com/aergoio/aergo-lib/db" "github.com/aergoio/aergo/v2/consensus" - "github.com/aergoio/aergo/v2/internal/enc" + "github.com/aergoio/aergo/v2/internal/enc/gob" "github.com/aergoio/aergo/v2/types" "github.com/aergoio/aergo/v2/types/dbkey" "github.com/aergoio/etcd/raft/raftpb" @@ -234,7 +234,7 @@ func (cdb *ChainDB) GetRaftEntry(idx uint64) (*consensus.WalEntry, error) { } var entry consensus.WalEntry - if err := enc.GobDecode(data, &entry); err != nil { + if err := gob.Decode(data, &entry); err != nil { return nil, err } @@ -421,7 +421,7 @@ func (cdb *ChainDB) WriteIdentity(identity *consensus.RaftIdentity) error { logger.Info().Str("id", identity.ToString()).Msg("save raft identity") - enc, err := enc.GobEncode(identity) + enc, err := gob.Encode(identity) if err != nil { return ErrEncodeRaftIdentity } @@ -439,7 +439,7 @@ func (cdb *ChainDB) GetIdentity() (*consensus.RaftIdentity, error) { } var id consensus.RaftIdentity - if err := enc.GobDecode(data, &id); err != nil { + if err := gob.Decode(data, &id); err != nil { return nil, ErrDecodeRaftIdentity } diff --git a/chain/chainhandle.go b/chain/chainhandle.go index a76eacb85..12a8abd32 100644 --- a/chain/chainhandle.go +++ b/chain/chainhandle.go @@ -18,7 +18,7 @@ import ( "github.com/aergoio/aergo/v2/contract" "github.com/aergoio/aergo/v2/contract/name" "github.com/aergoio/aergo/v2/contract/system" - "github.com/aergoio/aergo/v2/internal/enc" + "github.com/aergoio/aergo/v2/internal/enc/base58" "github.com/aergoio/aergo/v2/message" "github.com/aergoio/aergo/v2/state" "github.com/aergoio/aergo/v2/types" @@ -55,7 +55,7 @@ type ErrBlock struct { } func (ec *ErrBlock) Error() string { - return fmt.Sprintf("Error: %s. block(%s, %d)", ec.err.Error(), enc.B58Encode(ec.block.Hash), ec.block.No) + return fmt.Sprintf("Error: %s. block(%s, %d)", ec.err.Error(), base58.Encode(ec.block.Hash), ec.block.No) } type ErrTx struct { @@ -64,7 +64,7 @@ type ErrTx struct { } func (ec *ErrTx) Error() string { - return fmt.Sprintf("error executing tx:%s, tx=%s", ec.err.Error(), enc.B58Encode(ec.tx.GetHash())) + return fmt.Sprintf("error executing tx:%s, tx=%s", ec.err.Error(), base58.Encode(ec.tx.GetHash())) } func (cs *ChainService) getBestBlockNo() types.BlockNo { @@ -288,7 +288,7 @@ func (cp *chainProcessor) addBlock(blk *types.Block) error { Uint64("latest", cp.cdb.getBestBlockNo()). Uint64("blockNo", blk.BlockNo()). Str("hash", blk.ID()). - Str("prev_hash", enc.B58Encode(blk.GetHeader().GetPrevBlockHash())). + Str("prev_hash", base58.Encode(blk.GetHeader().GetPrevBlockHash())). Msg("block added to the block indices") } cp.lastBlock = blk @@ -637,7 +637,7 @@ func NewTxExecutor(execCtx context.Context, ccc consensus.ChainConsensusCluster, err := executeTx(execCtx, ccc, cdb, bState, tx, bi, preloadService) if err != nil { - logger.Error().Err(err).Str("hash", enc.B58Encode(tx.GetHash())).Msg("tx failed") + logger.Error().Err(err).Str("hash", base58.Encode(tx.GetHash())).Msg("tx failed") if err2 := bState.Rollback(blockSnap); err2 != nil { logger.Panic().Err(err).Msg("failed to rollback block state") } @@ -949,7 +949,7 @@ func executeTx(execCtx context.Context, ccc consensus.ChainConsensusCluster, cdb txFee = new(big.Int).SetUint64(0) events, err = executeGovernanceTx(ccc, bs, txBody, sender, receiver, bi) if err != nil { - logger.Warn().Err(err).Str("txhash", enc.B58Encode(tx.GetHash())).Msg("governance tx Error") + logger.Warn().Err(err).Str("txhash", base58.Encode(tx.GetHash())).Msg("governance tx Error") } case types.TxType_FEEDELEGATION: balance := receiver.Balance() @@ -970,7 +970,7 @@ func executeTx(execCtx context.Context, ccc consensus.ChainConsensusCluster, cdb tx.GetHash(), txBody.GetAccount(), txBody.GetAmount()) if err != nil { if err != types.ErrNotAllowedFeeDelegation { - logger.Warn().Err(err).Str("txhash", enc.B58Encode(tx.GetHash())).Msg("checkFeeDelegation Error") + logger.Warn().Err(err).Str("txhash", base58.Encode(tx.GetHash())).Msg("checkFeeDelegation Error") return err } return types.ErrNotAllowedFeeDelegation diff --git a/chain/chainservice.go b/chain/chainservice.go index b7fb7e3b3..7b4b0aaea 100644 --- a/chain/chainservice.go +++ b/chain/chainservice.go @@ -24,7 +24,7 @@ import ( "github.com/aergoio/aergo/v2/contract/name" "github.com/aergoio/aergo/v2/contract/system" "github.com/aergoio/aergo/v2/fee" - "github.com/aergoio/aergo/v2/internal/enc" + "github.com/aergoio/aergo/v2/internal/enc/base58" "github.com/aergoio/aergo/v2/message" "github.com/aergoio/aergo/v2/pkg/component" "github.com/aergoio/aergo/v2/state" @@ -145,7 +145,7 @@ func (core *Core) initGenesis(genesis *types.Genesis, mainnet bool, testmode boo genesisBlock, _ := core.cdb.GetBlockByNo(0) logger.Info().Str("chain id", gen.ID.ToJSON()). - Str("hash", enc.B58Encode(genesisBlock.GetHash())).Msg("chain initialized") + Str("hash", base58.Encode(genesisBlock.GetHash())).Msg("chain initialized") return genesisBlock, nil } @@ -274,7 +274,7 @@ func NewChainService(cfg *cfg.Config) *ChainService { logger.Debug().Err(err).Msg("failed to get elected BPs") } else { for _, res := range top.Votes { - logger.Debug().Str("BP", enc.B58Encode(res.Candidate)). + logger.Debug().Str("BP", base58.Encode(res.Candidate)). Str("votes", new(big.Int).SetBytes(res.Amount).String()).Msgf("BP vote stat") } } @@ -641,7 +641,7 @@ func (cm *ChainManager) Receive(context actor.Context) { bstate = msg.Bstate.(*state.BlockState) if timeoutTx := bstate.TimeoutTx(); timeoutTx != nil { if logger.IsDebugEnabled() { - logger.Debug().Str("hash", enc.B58Encode(timeoutTx.GetHash())).Msg("received timeout tx") + logger.Debug().Str("hash", base58.Encode(timeoutTx.GetHash())).Msg("received timeout tx") } cm.TellTo(message.MemPoolSvc, &message.MemPoolDelTx{Tx: timeoutTx.GetTx()}) } @@ -686,7 +686,7 @@ func getAddressNameResolved(sdb *state.StateDB, account []byte) ([]byte, error) if len(account) == types.NameLength { scs, err := sdb.GetNameAccountState() if err != nil { - logger.Error().Str("hash", enc.B58Encode(account)).Err(err).Msg("failed to get state for account") + logger.Error().Str("hash", base58.Encode(account)).Err(err).Msg("failed to get state for account") return nil, err } return name.GetAddress(scs, account), nil @@ -705,7 +705,7 @@ func (cw *ChainWorker) Receive(context actor.Context) { id := types.ToAccountID(address) proof, err := sdb.GetAccountAndProof(id[:], root, compressed) if err != nil { - logger.Error().Str("hash", enc.B58Encode(address)).Err(err).Msg("failed to get state for account") + logger.Error().Str("hash", base58.Encode(address)).Err(err).Msg("failed to get state for account") return nil, err } proof.Key = address @@ -717,7 +717,7 @@ func (cw *ChainWorker) Receive(context actor.Context) { bid := types.ToBlockID(msg.BlockHash) block, err := cw.getBlock(bid[:]) if err != nil { - logger.Debug().Err(err).Str("hash", enc.B58Encode(msg.BlockHash)).Msg("block not found") + logger.Debug().Err(err).Str("hash", base58.Encode(msg.BlockHash)).Msg("block not found") } context.Respond(message.GetBlockRsp{ Block: block, @@ -746,7 +746,7 @@ func (cw *ChainWorker) Receive(context actor.Context) { id := types.ToAccountID(address) accState, err := sdb.GetAccountState(id) if err != nil { - logger.Error().Str("hash", enc.B58Encode(address)).Err(err).Msg("failed to get state for account") + logger.Error().Str("hash", base58.Encode(address)).Err(err).Msg("failed to get state for account") } context.Respond(message.GetStateRsp{ Account: address, @@ -807,7 +807,7 @@ func (cw *ChainWorker) Receive(context actor.Context) { } ctrState, err := sdb.OpenContractStateAccount(types.ToAccountID(address)) if err != nil { - logger.Error().Str("hash", enc.B58Encode(address)).Err(err).Msg("failed to get state for contract") + logger.Error().Str("hash", base58.Encode(address)).Err(err).Msg("failed to get state for contract") context.Respond(message.GetQueryRsp{Result: nil, Err: err}) } else { bs := state.NewBlockState(sdb) @@ -833,7 +833,7 @@ func (cw *ChainWorker) Receive(context actor.Context) { varProof.Key = storageKey varProofs = append(varProofs, varProof) if err != nil { - logger.Error().Str("hash", enc.B58Encode(contractProof.Key)).Err(err).Msg("failed to get state variable in contract") + logger.Error().Str("hash", base58.Encode(contractProof.Key)).Err(err).Msg("failed to get state variable in contract") } } } @@ -895,7 +895,7 @@ func (cw *ChainWorker) Receive(context actor.Context) { sdb = cw.sdb.OpenNewStateDB(cw.sdb.GetRoot()) ctrState, err := sdb.OpenContractStateAccount(types.ToAccountID(msg.Contract)) if err != nil { - logger.Error().Str("hash", enc.B58Encode(msg.Contract)).Err(err).Msg("failed to get state for contract") + logger.Error().Str("hash", base58.Encode(msg.Contract)).Err(err).Msg("failed to get state for contract") context.Respond(message.CheckFeeDelegationRsp{Err: err}) } else { bs := state.NewBlockState(sdb) diff --git a/chain/chainverifier.go b/chain/chainverifier.go index 3fd86bfb3..811edc8ea 100644 --- a/chain/chainverifier.go +++ b/chain/chainverifier.go @@ -6,7 +6,7 @@ import ( "time" "github.com/aergoio/aergo-actor/actor" - "github.com/aergoio/aergo/v2/internal/enc" + "github.com/aergoio/aergo/v2/internal/enc/base58" "github.com/aergoio/aergo/v2/message" "github.com/aergoio/aergo/v2/pkg/component" "github.com/aergoio/aergo/v2/types" @@ -189,14 +189,14 @@ func (cv *ChainVerifier) report(prevBlock *types.Block, targetBlock *types.Block switch cv.stage { case TestPrevBlock: report += fmt.Sprintf("[description] prev block hash=%s, prev stage root=%s", prevBlock.ID(), - enc.B58Encode(prevBlock.GetHeader().GetBlocksRootHash())) + base58.Encode(prevBlock.GetHeader().GetBlocksRootHash())) case TestCurBlock: report += fmt.Sprintf("[description] target block hash=%s", targetBlock.ID()) case TestBlockExecute: - report += fmt.Sprintf("[description] tx Merkle = %s", enc.B58Encode(targetBlock.GetHeader().GetTxsRootHash())) - report += fmt.Sprintf(", state Root = %s", enc.B58Encode(targetBlock.GetHeader().GetBlocksRootHash())) + report += fmt.Sprintf("[description] tx Merkle = %s", base58.Encode(targetBlock.GetHeader().GetTxsRootHash())) + report += fmt.Sprintf(", state Root = %s", base58.Encode(targetBlock.GetHeader().GetBlocksRootHash())) report += fmt.Sprintf(", all transaction passed") } diff --git a/chain/common.go b/chain/common.go index 1556a48d8..fa8c2f79d 100644 --- a/chain/common.go +++ b/chain/common.go @@ -9,7 +9,7 @@ import ( "errors" "github.com/aergoio/aergo/v2/consensus" - "github.com/aergoio/aergo/v2/internal/enc" + "github.com/aergoio/aergo/v2/internal/enc/base58" "github.com/aergoio/aergo/v2/types" ) @@ -48,7 +48,7 @@ func Init(maxBlkBodySize uint32, coinbaseAccountStr string, isBp bool, maxAnchor if err != nil { return ErrInvalidCoinbaseAccount } - logger.Info().Str("account", enc.B58Encode(CoinbaseAccount)).Str("str", coinbaseAccountStr). + logger.Info().Str("account", base58.Encode(CoinbaseAccount)).Str("str", coinbaseAccountStr). Msg("set coinbase account") } else { diff --git a/chain/orphanpool.go b/chain/orphanpool.go index edc79749a..2c49d7860 100644 --- a/chain/orphanpool.go +++ b/chain/orphanpool.go @@ -9,7 +9,7 @@ import ( "errors" "sync" - "github.com/aergoio/aergo/v2/internal/enc" + "github.com/aergoio/aergo/v2/internal/enc/base58" "github.com/aergoio/aergo/v2/types" "github.com/hashicorp/golang-lru/simplelru" ) @@ -51,7 +51,7 @@ func NewOrphanPool(size int) *OrphanPool { // add Orphan into the orphan cache pool func (op *OrphanPool) addOrphan(block *types.Block) error { - logger.Warn().Str("prev", enc.B58Encode(block.GetHeader().GetPrevBlockHash())).Msg("add orphan Block") + logger.Warn().Str("prev", base58.Encode(block.GetHeader().GetPrevBlockHash())).Msg("add orphan Block") id := types.ToBlockID(block.Header.PrevBlockHash) cachedblock, exists := op.cache[id] diff --git a/chain/recover.go b/chain/recover.go index 51e736a14..26e14ee74 100644 --- a/chain/recover.go +++ b/chain/recover.go @@ -8,7 +8,8 @@ import ( "runtime" "runtime/debug" - "github.com/aergoio/aergo/v2/internal/enc" + "github.com/aergoio/aergo/v2/internal/enc/base58" + "github.com/aergoio/aergo/v2/internal/enc/gob" "github.com/aergoio/aergo/v2/types" "github.com/aergoio/aergo/v2/types/dbkey" ) @@ -62,7 +63,7 @@ func (cs *ChainService) Recover() error { // check status of chain if !bytes.Equal(best.BlockHash(), marker.BrBestHash) { - logger.Error().Str("best", best.ID()).Str("markerbest", enc.B58Encode(marker.BrBestHash)).Msg("best block is not equal to old chain") + logger.Error().Str("best", best.ID()).Str("markerbest", base58.Encode(marker.BrBestHash)).Msg("best block is not equal to old chain") return ErrRecoInvalidBest } @@ -217,20 +218,20 @@ func (rm *ReorgMarker) delete() { } func (rm *ReorgMarker) toBytes() ([]byte, error) { - return enc.GobEncode(rm) + return gob.Encode(rm) } func (rm *ReorgMarker) toString() string { buf := "" if len(rm.BrStartHash) != 0 { - buf = buf + fmt.Sprintf("branch root=(%d, %s).", rm.BrStartNo, enc.B58Encode(rm.BrStartHash)) + buf = buf + fmt.Sprintf("branch root=(%d, %s).", rm.BrStartNo, base58.Encode(rm.BrStartHash)) } if len(rm.BrTopHash) != 0 { - buf = buf + fmt.Sprintf("branch top=(%d, %s).", rm.BrTopNo, enc.B58Encode(rm.BrTopHash)) + buf = buf + fmt.Sprintf("branch top=(%d, %s).", rm.BrTopNo, base58.Encode(rm.BrTopHash)) } if len(rm.BrBestHash) != 0 { - buf = buf + fmt.Sprintf("org best=(%d, %s).", rm.BrBestNo, enc.B58Encode(rm.BrBestHash)) + buf = buf + fmt.Sprintf("org best=(%d, %s).", rm.BrBestNo, base58.Encode(rm.BrBestHash)) } return buf diff --git a/chain/reorg.go b/chain/reorg.go index 91dc1c636..c4107c634 100644 --- a/chain/reorg.go +++ b/chain/reorg.go @@ -8,7 +8,7 @@ import ( "github.com/aergoio/aergo/v2/consensus" "github.com/aergoio/aergo/v2/contract/system" - "github.com/aergoio/aergo/v2/internal/enc" + "github.com/aergoio/aergo/v2/internal/enc/base58" "github.com/aergoio/aergo/v2/message" "github.com/aergoio/aergo/v2/state" "github.com/aergoio/aergo/v2/types" @@ -52,7 +52,7 @@ type ErrReorgBlock struct { func (ec *ErrReorgBlock) Error() string { if ec.blockHash != nil { - return fmt.Sprintf("%s, block:%d,%s", ec.msg, ec.blockNo, enc.B58Encode(ec.blockHash)) + return fmt.Sprintf("%s, block:%d,%s", ec.msg, ec.blockNo, base58.Encode(ec.blockHash)) } else if ec.blockNo != 0 { return fmt.Sprintf("%s, block:%d", ec.msg, ec.blockNo) } else { diff --git a/chain/signVerifier.go b/chain/signVerifier.go index 304b12fae..6240e88bf 100644 --- a/chain/signVerifier.go +++ b/chain/signVerifier.go @@ -7,7 +7,7 @@ import ( "github.com/aergoio/aergo-actor/actor" "github.com/aergoio/aergo/v2/account/key" "github.com/aergoio/aergo/v2/contract/name" - "github.com/aergoio/aergo/v2/internal/enc" + "github.com/aergoio/aergo/v2/internal/enc/base58" "github.com/aergoio/aergo/v2/message" "github.com/aergoio/aergo/v2/pkg/component" "github.com/aergoio/aergo/v2/state" @@ -83,7 +83,7 @@ func (sv *SignVerifier) verifyTxLoop(workerNo int) { hit, err := sv.verifyTx(sv.comm, txWork.tx, txWork.useMempool) if err != nil { - logger.Error().Int("worker", workerNo).Bool("hit", hit).Str("hash", enc.B58Encode(txWork.tx.GetHash())). + logger.Error().Int("worker", workerNo).Bool("hit", hit).Str("hash", base58.Encode(txWork.tx.GetHash())). Err(err).Msg("error verify tx") } diff --git a/cmd/aergocli/cmd/blockchain_test.go b/cmd/aergocli/cmd/blockchain_test.go index c8cc03892..271f32234 100644 --- a/cmd/aergocli/cmd/blockchain_test.go +++ b/cmd/aergocli/cmd/blockchain_test.go @@ -4,7 +4,8 @@ import ( "testing" "github.com/aergoio/aergo/v2/cmd/aergocli/util/encoding/json" - "github.com/aergoio/aergo/v2/internal/enc" + "github.com/aergoio/aergo/v2/internal/enc/base58" + "github.com/aergoio/aergo/v2/internal/enc/hex" "github.com/aergoio/aergo/v2/types" "github.com/golang/mock/gomock" "github.com/stretchr/testify/assert" @@ -15,7 +16,7 @@ func TestBlockchainWithMock(t *testing.T) { defer deinitMock() testBlockHashString := "56Qy6MQei9KM13rqEq1jiJ7Da21Kcq9KdmYWcnPLtxS3" - testBlockHash, _ := enc.B58Decode(testBlockHashString) + testBlockHash, _ := base58.Decode(testBlockHashString) mock.EXPECT().Blockchain( gomock.Any(), // expect any value for first parameter @@ -47,7 +48,7 @@ func TestBlockchainWithMock(t *testing.T) { if err := json.Unmarshal([]byte(output), &result); err != nil { t.Fatal(err) } - testBlockHashByte, _ := enc.B58Decode(testBlockHashString) - assert.Equal(t, enc.HexEncode(testBlockHashByte), result["Hash"]) + testBlockHashByte, _ := base58.Decode(testBlockHashString) + assert.Equal(t, hex.Encode(testBlockHashByte), result["Hash"]) assert.Equal(t, float64(1), result["Height"]) } diff --git a/cmd/aergocli/cmd/committx_test.go b/cmd/aergocli/cmd/committx_test.go index 4259cebf9..aa5eb00fd 100644 --- a/cmd/aergocli/cmd/committx_test.go +++ b/cmd/aergocli/cmd/committx_test.go @@ -4,7 +4,7 @@ import ( "testing" "github.com/aergoio/aergo/v2/cmd/aergocli/util/encoding/json" - "github.com/aergoio/aergo/v2/internal/enc" + "github.com/aergoio/aergo/v2/internal/enc/base58" "github.com/aergoio/aergo/v2/types" "github.com/golang/mock/gomock" "github.com/stretchr/testify/assert" @@ -15,7 +15,7 @@ func TestCommitTxWithMock(t *testing.T) { defer deinitMock() testTxHashString := "HB44gJvHhVoEfgiGq3VZmV9VUXfBXhHjcEvroBMkJGnY" - testTxHash, _ := enc.B58Decode(testTxHashString) + testTxHash, _ := base58.Decode(testTxHashString) output, err := executeCommand(rootCmd, "committx", "--jsontx", "{}") assert.Error(t, err, "should occur error when empty json") @@ -56,5 +56,5 @@ func TestCommitTxWithMock(t *testing.T) { output, err = executeCommand(rootCmd, "committx", "--jsontx", "{ \"Hash\": \"HB44gJvHhVoEfgiGq3VZmV9VUXfBXhHjcEvroBMkJGnY\", \"Body\": {\"Nonce\": 2, \"Account\": \"AmNBZ8WQKP8DbuP9Q9W9vGFhiT8vQNcuSZ2SbBbVvbJWGV3Wh1mn\", \"Recipient\": \"AmLnVfGwq49etaa7dnzfGJTbaZWV7aVmrxFes4KmWukXwtooVZPJ\", \"Amount\": \"25000\", \"Payload\": \"\", \"Limit\": 100, \"Price\": \"1\", \"Type\": 0, \"Sign\": \"381yXYxTtq2tRPRQPF7tHH6Cq3y8PvcsFWztPwCRmmYfqnK83Z3a6Yj9fyy8Rpvrrw76Y52SNAP6Th3BYQjX1Bcmf6NQrDHQ\"}}") err = json.Unmarshal([]byte(output), out) assert.NoError(t, err, "should no error") - assert.Equal(t, "HB44gJvHhVoEfgiGq3VZmV9VUXfBXhHjcEvroBMkJGnY", enc.B58Encode(out.GetResults()[0].Hash)) + assert.Equal(t, "HB44gJvHhVoEfgiGq3VZmV9VUXfBXhHjcEvroBMkJGnY", base58.Encode(out.GetResults()[0].Hash)) } diff --git a/cmd/aergocli/cmd/contract.go b/cmd/aergocli/cmd/contract.go index 68fb90072..010b7f6ac 100644 --- a/cmd/aergocli/cmd/contract.go +++ b/cmd/aergocli/cmd/contract.go @@ -13,7 +13,8 @@ import ( luacEncoding "github.com/aergoio/aergo/v2/cmd/aergoluac/encoding" luac "github.com/aergoio/aergo/v2/cmd/aergoluac/util" "github.com/aergoio/aergo/v2/internal/common" - "github.com/aergoio/aergo/v2/internal/enc" + "github.com/aergoio/aergo/v2/internal/enc/base58" + "github.com/aergoio/aergo/v2/internal/enc/hex" "github.com/aergoio/aergo/v2/types" aergorpc "github.com/aergoio/aergo/v2/types" "github.com/spf13/cobra" @@ -200,7 +201,7 @@ func runDeployCmd(cmd *cobra.Command, args []string) error { if isHexString(data) { // the data is expected to be copied from aergoscan view of // the transaction that deployed the contract - payload, err = enc.HexDecode(data) + payload, err = hex.Decode(data) } else { // the data is the output of aergoluac code, err = luacEncoding.DecodeCode(data) @@ -310,7 +311,7 @@ func runCallCmd(cmd *cobra.Command, args []string) error { } if chainIdHash != "" { - rawCidHash, err := enc.B58Decode(chainIdHash) + rawCidHash, err := base58.Decode(chainIdHash) if err != nil { return fmt.Errorf("failed to parse chainidhash: %v", err.Error()) } @@ -413,7 +414,7 @@ func runQueryStateCmd(cmd *cobra.Command, args []string) error { return fmt.Errorf("failed to decode address: %v", err.Error()) } if len(stateroot) != 0 { - root, err = enc.B58Decode(stateroot) + root, err = base58.Decode(stateroot) if err != nil { return fmt.Errorf("failed to decode stateroot: %v", err.Error()) } diff --git a/cmd/aergocli/cmd/enterprise.go b/cmd/aergocli/cmd/enterprise.go index f9d280428..ed57846d4 100644 --- a/cmd/aergocli/cmd/enterprise.go +++ b/cmd/aergocli/cmd/enterprise.go @@ -16,7 +16,7 @@ import ( "github.com/aergoio/aergo/v2/cmd/aergocli/util" "github.com/aergoio/aergo/v2/cmd/aergocli/util/encoding/json" "github.com/aergoio/aergo/v2/contract/enterprise" - "github.com/aergoio/aergo/v2/internal/enc" + "github.com/aergoio/aergo/v2/internal/enc/base58" "github.com/aergoio/aergo/v2/types" aergorpc "github.com/aergoio/aergo/v2/types" "github.com/spf13/cobra" @@ -155,7 +155,7 @@ var enterpriseTxCmd = &cobra.Command{ Short: "Print transaction for enterprise", Args: cobra.MinimumNArgs(1), Run: func(cmd *cobra.Command, args []string) { - txHashDecode, err := enc.B58Decode(args[0]) + txHashDecode, err := base58.Decode(args[0]) if err != nil { cmd.Println("Failed: invalid tx hash") return diff --git a/cmd/aergocli/cmd/enterprise_test.go b/cmd/aergocli/cmd/enterprise_test.go index 139698026..a9ddd1faf 100644 --- a/cmd/aergocli/cmd/enterprise_test.go +++ b/cmd/aergocli/cmd/enterprise_test.go @@ -5,7 +5,7 @@ import ( "errors" "testing" - "github.com/aergoio/aergo/v2/internal/enc" + "github.com/aergoio/aergo/v2/internal/enc/base58" aergorpc "github.com/aergoio/aergo/v2/types" "github.com/golang/mock/gomock" "github.com/stretchr/testify/assert" @@ -17,9 +17,9 @@ func TestGetConfChangeWithMock(t *testing.T) { var ( testTxHashString = "HB44gJvHhVoEfgiGq3VZmV9VUXfBXhHjcEvroBMkJGnY" - testTxHash, _ = enc.B58Decode(testTxHashString) + testTxHash, _ = base58.Decode(testTxHashString) testBlockHashString = "56Qy6MQei9KM13rqEq1jiJ7Da21Kcq9KdmYWcnPLtxS3" - testBlockHash, _ = enc.B58Decode(testBlockHashString) + testBlockHash, _ = base58.Decode(testBlockHashString) tx *aergorpc.Tx = &aergorpc.Tx{Hash: testTxHash, Body: &aergorpc.TxBody{Payload: []byte(string("{ \"name\": \"GetConfTest\" }"))}} resTxInBlock *aergorpc.TxInBlock = &aergorpc.TxInBlock{TxIdx: &aergorpc.TxIdx{BlockHash: testBlockHash, Idx: 1}, Tx: tx} diff --git a/cmd/aergocli/cmd/getblock.go b/cmd/aergocli/cmd/getblock.go index f2c0d86c3..f54e43dbb 100644 --- a/cmd/aergocli/cmd/getblock.go +++ b/cmd/aergocli/cmd/getblock.go @@ -12,7 +12,7 @@ import ( "fmt" "github.com/aergoio/aergo/v2/cmd/aergocli/util" - "github.com/aergoio/aergo/v2/internal/enc" + "github.com/aergoio/aergo/v2/internal/enc/base58" aergorpc "github.com/aergoio/aergo/v2/types" "github.com/spf13/cobra" ) @@ -56,7 +56,7 @@ func getSingleBlock(cmd *cobra.Command) error { binary.LittleEndian.PutUint64(b, uint64(number)) blockQuery = b } else { - decoded, err := enc.B58Decode(hash) + decoded, err := base58.Decode(hash) if err != nil { return fmt.Errorf("failed to decode block hash: %v", err) } diff --git a/cmd/aergocli/cmd/getstate.go b/cmd/aergocli/cmd/getstate.go index e39be0775..7e3080523 100644 --- a/cmd/aergocli/cmd/getstate.go +++ b/cmd/aergocli/cmd/getstate.go @@ -9,7 +9,7 @@ import ( "context" "github.com/aergoio/aergo/v2/cmd/aergocli/util" - "github.com/aergoio/aergo/v2/internal/enc" + "github.com/aergoio/aergo/v2/internal/enc/base58" "github.com/aergoio/aergo/v2/types" "github.com/spf13/cobra" ) @@ -35,7 +35,7 @@ func execGetState(cmd *cobra.Command, args []string) { var root []byte var err error if len(stateroot) != 0 { - root, err = enc.B58Decode(stateroot) + root, err = base58.Decode(stateroot) if err != nil { cmd.Printf("decode error: %s", err.Error()) return diff --git a/cmd/aergocli/cmd/gettx.go b/cmd/aergocli/cmd/gettx.go index 3013d450e..a122aec0c 100644 --- a/cmd/aergocli/cmd/gettx.go +++ b/cmd/aergocli/cmd/gettx.go @@ -9,7 +9,7 @@ import ( "context" "github.com/aergoio/aergo/v2/cmd/aergocli/util" - "github.com/aergoio/aergo/v2/internal/enc" + "github.com/aergoio/aergo/v2/internal/enc/base58" aergorpc "github.com/aergoio/aergo/v2/types" "github.com/spf13/cobra" ) @@ -30,7 +30,7 @@ func init() { } func execGetTX(cmd *cobra.Command, args []string) { - txHash, err := enc.B58Decode(args[0]) + txHash, err := base58.Decode(args[0]) if err != nil { cmd.Printf("Failed decode: %s", err.Error()) return diff --git a/cmd/aergocli/cmd/keygen.go b/cmd/aergocli/cmd/keygen.go index 6a26be7f8..ef553d154 100644 --- a/cmd/aergocli/cmd/keygen.go +++ b/cmd/aergocli/cmd/keygen.go @@ -9,7 +9,7 @@ import ( "github.com/aergoio/aergo/v2/account/key" keycrypto "github.com/aergoio/aergo/v2/account/key/crypto" - "github.com/aergoio/aergo/v2/internal/enc" + "github.com/aergoio/aergo/v2/internal/enc/base64" "github.com/aergoio/aergo/v2/p2p/p2putil" "github.com/aergoio/aergo/v2/types" "github.com/btcsuite/btcd/btcec" @@ -195,7 +195,7 @@ func generateKeyJson(priv crypto.PrivKey, pub crypto.PubKey) error { addressEncoded := types.EncodeAddress(address) jsonMarshalled, err := json.MarshalIndent(keyJson{ Address: addressEncoded, - PubKey: enc.B64Encode(pubBytes), + PubKey: base64.Encode(pubBytes), PrivKey: types.EncodePrivKey(privKeyExport), Id: types.IDB58Encode(pid), }, "", " ") diff --git a/cmd/aergocli/cmd/listblocks.go b/cmd/aergocli/cmd/listblocks.go index bc1b4dc0c..aa4c1c003 100644 --- a/cmd/aergocli/cmd/listblocks.go +++ b/cmd/aergocli/cmd/listblocks.go @@ -9,7 +9,7 @@ import ( "context" "github.com/aergoio/aergo/v2/cmd/aergocli/util" - "github.com/aergoio/aergo/v2/internal/enc" + "github.com/aergoio/aergo/v2/internal/enc/base58" "github.com/aergoio/aergo/v2/types" "github.com/spf13/cobra" ) @@ -41,7 +41,7 @@ func execListBlockHeaders(cmd *cobra.Command, args []string) { var err error if cmd.Flags().Changed("hash") == true { - blockHash, err = enc.B58Decode(gbhHash) + blockHash, err = base58.Decode(gbhHash) if err != nil { cmd.Printf("Failed: %s", err.Error()) return diff --git a/cmd/aergocli/cmd/receipt.go b/cmd/aergocli/cmd/receipt.go index 4b8c207eb..c36945556 100644 --- a/cmd/aergocli/cmd/receipt.go +++ b/cmd/aergocli/cmd/receipt.go @@ -10,7 +10,7 @@ import ( "log" "github.com/aergoio/aergo/v2/cmd/aergocli/util" - "github.com/aergoio/aergo/v2/internal/enc" + "github.com/aergoio/aergo/v2/internal/enc/base58" aergorpc "github.com/aergoio/aergo/v2/types" "github.com/spf13/cobra" ) @@ -28,7 +28,7 @@ func init() { Short: "Get a receipt", Args: cobra.MinimumNArgs(1), Run: func(cmd *cobra.Command, args []string) { - txHash, err := enc.B58Decode(args[0]) + txHash, err := base58.Decode(args[0]) if err != nil { log.Fatal(err) } diff --git a/cmd/aergocli/cmd/sendtx.go b/cmd/aergocli/cmd/sendtx.go index 9bd3f8b09..0b01d7df6 100644 --- a/cmd/aergocli/cmd/sendtx.go +++ b/cmd/aergocli/cmd/sendtx.go @@ -10,7 +10,7 @@ import ( "errors" "github.com/aergoio/aergo/v2/cmd/aergocli/util" - "github.com/aergoio/aergo/v2/internal/enc" + "github.com/aergoio/aergo/v2/internal/enc/base58" "github.com/aergoio/aergo/v2/types" "github.com/spf13/cobra" ) @@ -59,7 +59,7 @@ func execSendTX(cmd *cobra.Command, args []string) error { GasLimit: gas, }} if chainIdHash != "" { - cid, err := enc.B58Decode(chainIdHash) + cid, err := base58.Decode(chainIdHash) if err != nil { return errors.New("Wrong value in --chainidhash flag\n" + err.Error()) } diff --git a/cmd/aergocli/cmd/sendtx_test.go b/cmd/aergocli/cmd/sendtx_test.go index a4b35f872..cec44f02e 100644 --- a/cmd/aergocli/cmd/sendtx_test.go +++ b/cmd/aergocli/cmd/sendtx_test.go @@ -4,7 +4,7 @@ import ( "testing" "github.com/aergoio/aergo/v2/cmd/aergocli/util/encoding/json" - "github.com/aergoio/aergo/v2/internal/enc" + "github.com/aergoio/aergo/v2/internal/enc/base58" "github.com/aergoio/aergo/v2/types" "github.com/golang/mock/gomock" "github.com/stretchr/testify/assert" @@ -15,7 +15,7 @@ func TestSendTxWithMock(t *testing.T) { defer deinitMock() testTxHashString := "BdAoKcLSsrscjdpTPGe9DoFsz4mP9ezbc4Dk5fuBTT4e" - testTxHash, _ := enc.B58Decode(testTxHashString) + testTxHash, _ := base58.Decode(testTxHashString) mock.EXPECT().SendTX( gomock.Any(), // expect any value for first parameter @@ -34,7 +34,7 @@ func TestSendTxWithMock(t *testing.T) { t.Log(output) out := &types.CommitResult{} err = json.Unmarshal([]byte(output), out) - assert.Equal(t, testTxHashString, enc.B58Encode(out.Hash)) + assert.Equal(t, testTxHashString, base58.Encode(out.Hash)) } func TestSendTxFromToValidation(t *testing.T) { diff --git a/cmd/aergocli/cmd/signtx.go b/cmd/aergocli/cmd/signtx.go index a2aa1e245..748784ff1 100644 --- a/cmd/aergocli/cmd/signtx.go +++ b/cmd/aergocli/cmd/signtx.go @@ -8,7 +8,7 @@ import ( "github.com/aergoio/aergo/v2/account/key" crypto "github.com/aergoio/aergo/v2/account/key/crypto" "github.com/aergoio/aergo/v2/cmd/aergocli/util" - "github.com/aergoio/aergo/v2/internal/enc" + "github.com/aergoio/aergo/v2/internal/enc/base58" "github.com/aergoio/aergo/v2/types" "github.com/btcsuite/btcd/btcec" "github.com/spf13/cobra" @@ -44,7 +44,7 @@ var signCmd = &cobra.Command{ var msg *types.Tx if privKey != "" { - rawKey, err := enc.B58Decode(privKey) + rawKey, err := base58.Decode(privKey) if err != nil { cmd.Printf("Failed: %s\n", err.Error()) return diff --git a/cmd/aergocli/cmd/signtx_test.go b/cmd/aergocli/cmd/signtx_test.go index a0a0371c6..972aca344 100644 --- a/cmd/aergocli/cmd/signtx_test.go +++ b/cmd/aergocli/cmd/signtx_test.go @@ -8,7 +8,7 @@ import ( "github.com/aergoio/aergo/v2/cmd/aergocli/util" "github.com/aergoio/aergo/v2/cmd/aergocli/util/encoding/json" - "github.com/aergoio/aergo/v2/internal/enc" + "github.com/aergoio/aergo/v2/internal/enc/base58" "github.com/aergoio/aergo/v2/types" "github.com/stretchr/testify/assert" ) @@ -30,7 +30,7 @@ func TestSignWithKey(t *testing.T) { err = json.Unmarshal([]byte(ouputjson), &tx) assert.NoError(t, err, "should be success") - sign, err := enc.B58Decode(tx.Body.Sign) + sign, err := base58.Decode(tx.Body.Sign) assert.NoError(t, err, "should be success") assert.Equalf(t, len(sign), signLength, "wrong sign length value = %s", tx.Body.Sign) } diff --git a/cmd/aergocli/cmd/vote.go b/cmd/aergocli/cmd/vote.go index 31514f8a4..122c35441 100644 --- a/cmd/aergocli/cmd/vote.go +++ b/cmd/aergocli/cmd/vote.go @@ -13,7 +13,7 @@ import ( "strings" "github.com/aergoio/aergo/v2/cmd/aergocli/util" - "github.com/aergoio/aergo/v2/internal/enc" + "github.com/aergoio/aergo/v2/internal/enc/base58" "github.com/aergoio/aergo/v2/types" "github.com/spf13/cobra" ) @@ -84,7 +84,7 @@ func execVote(cmd *cobra.Command, args []string) { cmd.Println("too many candidates") return } - candidate, err := enc.B58Decode(v.(string)) + candidate, err := base58.Decode(v.(string)) if err != nil { cmd.Printf("Failed: %s (%s)\n", err.Error(), v) return @@ -176,7 +176,7 @@ func execBP(cmd *cobra.Command, args []string) { cmd.Println("[") comma := "," for i, r := range msg.GetVotes() { - cmd.Printf("{\"" + enc.B58Encode(r.Candidate) + "\":" + r.GetAmountBigInt().String() + "}") + cmd.Printf("{\"" + base58.Encode(r.Candidate) + "\":" + r.GetAmountBigInt().String() + "}") if i+1 == len(msg.GetVotes()) { comma = "" } diff --git a/cmd/aergocli/util/base58addr.go b/cmd/aergocli/util/base58addr.go index 585839ea6..c744d6591 100644 --- a/cmd/aergocli/util/base58addr.go +++ b/cmd/aergocli/util/base58addr.go @@ -8,7 +8,7 @@ import ( "strconv" "time" - "github.com/aergoio/aergo/v2/internal/enc" + "github.com/aergoio/aergo/v2/internal/enc/base58" "github.com/aergoio/aergo/v2/p2p/p2putil" "github.com/aergoio/aergo/v2/types" ) @@ -102,7 +102,7 @@ func FillTxBody(source *InOutTxBody, target *types.TxBody) error { target.Amount = amount.Bytes() } if source.Payload != "" { - target.Payload, err = enc.B58Decode(source.Payload) + target.Payload, err = base58.Decode(source.Payload) if err != nil { return err } @@ -116,13 +116,13 @@ func FillTxBody(source *InOutTxBody, target *types.TxBody) error { target.GasPrice = price.Bytes() } if source.ChainIdHash != "" { - target.ChainIdHash, err = enc.B58Decode(source.ChainIdHash) + target.ChainIdHash, err = base58.Decode(source.ChainIdHash) if err != nil { return err } } if source.Sign != "" { - target.Sign, err = enc.B58Decode(source.Sign) + target.Sign, err = base58.Decode(source.Sign) if err != nil { return err } @@ -146,7 +146,7 @@ func ParseBase58Tx(jsonTx []byte) ([]*types.Tx, error) { for i, in := range inputlist { tx := &types.Tx{Body: &types.TxBody{}} if in.Hash != "" { - tx.Hash, err = enc.B58Decode(in.Hash) + tx.Hash, err = base58.Decode(in.Hash) if err != nil { return nil, err } @@ -183,7 +183,7 @@ func ConvTxEx(tx *types.Tx, payloadType EncodingType) *InOutTx { if tx == nil { return out } - out.Hash = enc.B58Encode(tx.Hash) + out.Hash = base58.Encode(tx.Hash) out.Body.Nonce = tx.Body.Nonce if tx.Body.Account != nil { out.Body.Account = types.EncodeAddress(tx.Body.Account) @@ -198,21 +198,21 @@ func ConvTxEx(tx *types.Tx, payloadType EncodingType) *InOutTx { case Raw: out.Body.Payload = string(tx.Body.Payload) case Base58: - out.Body.Payload = enc.B58Encode(tx.Body.Payload) + out.Body.Payload = base58.Encode(tx.Body.Payload) } out.Body.GasLimit = tx.Body.GasLimit if tx.Body.GasPrice != nil { out.Body.GasPrice = new(big.Int).SetBytes(tx.Body.GasPrice).String() } - out.Body.ChainIdHash = enc.B58Encode(tx.Body.ChainIdHash) - out.Body.Sign = enc.B58Encode(tx.Body.Sign) + out.Body.ChainIdHash = base58.Encode(tx.Body.ChainIdHash) + out.Body.Sign = base58.Encode(tx.Body.Sign) out.Body.Type = tx.Body.Type return out } func ConvTxInBlockEx(txInBlock *types.TxInBlock, payloadType EncodingType) *InOutTxInBlock { out := &InOutTxInBlock{TxIdx: &InOutTxIdx{}, Tx: &InOutTx{}} - out.TxIdx.BlockHash = enc.B58Encode(txInBlock.GetTxIdx().GetBlockHash()) + out.TxIdx.BlockHash = base58.Encode(txInBlock.GetTxIdx().GetBlockHash()) out.TxIdx.Idx = txInBlock.GetTxIdx().GetIdx() out.Tx = ConvTxEx(txInBlock.GetTx(), payloadType) return out @@ -221,18 +221,18 @@ func ConvTxInBlockEx(txInBlock *types.TxInBlock, payloadType EncodingType) *InOu func ConvBlock(b *types.Block) *InOutBlock { out := &InOutBlock{} if b != nil { - out.Hash = enc.B58Encode(b.Hash) - out.Header.ChainID = enc.B58Encode(b.GetHeader().GetChainID()) + out.Hash = base58.Encode(b.Hash) + out.Header.ChainID = base58.Encode(b.GetHeader().GetChainID()) out.Header.Version = types.DecodeChainIdVersion(b.GetHeader().GetChainID()) - out.Header.PrevBlockHash = enc.B58Encode(b.GetHeader().GetPrevBlockHash()) + out.Header.PrevBlockHash = base58.Encode(b.GetHeader().GetPrevBlockHash()) out.Header.BlockNo = b.GetHeader().GetBlockNo() out.Header.Timestamp = b.GetHeader().GetTimestamp() - out.Header.BlockRootHash = enc.B58Encode(b.GetHeader().GetBlocksRootHash()) - out.Header.TxRootHash = enc.B58Encode(b.GetHeader().GetTxsRootHash()) - out.Header.ReceiptsRootHash = enc.B58Encode(b.GetHeader().GetReceiptsRootHash()) + out.Header.BlockRootHash = base58.Encode(b.GetHeader().GetBlocksRootHash()) + out.Header.TxRootHash = base58.Encode(b.GetHeader().GetTxsRootHash()) + out.Header.ReceiptsRootHash = base58.Encode(b.GetHeader().GetReceiptsRootHash()) out.Header.Confirms = b.GetHeader().GetConfirms() - out.Header.PubKey = enc.B58Encode(b.GetHeader().GetPubKey()) - out.Header.Sign = enc.B58Encode(b.GetHeader().GetSign()) + out.Header.PubKey = base58.Encode(b.GetHeader().GetPubKey()) + out.Header.Sign = base58.Encode(b.GetHeader().GetSign()) if b.GetHeader().GetCoinbaseAccount() != nil { out.Header.CoinbaseAccount = types.EncodeAddress(b.GetHeader().GetCoinbaseAccount()) } @@ -254,10 +254,10 @@ func ConvPeer(p *types.Peer) *InOutPeer { out.Role = p.AcceptedRole.String() out.Address.Address = p.GetAddress().GetAddress() out.Address.Port = strconv.Itoa(int(p.GetAddress().GetPort())) - out.Address.PeerId = enc.B58Encode(p.GetAddress().GetPeerID()) + out.Address.PeerId = base58.Encode(p.GetAddress().GetPeerID()) out.LastCheck = time.Unix(0, p.GetLashCheck()) out.BestBlock.BlockNo = p.GetBestblock().GetBlockNo() - out.BestBlock.BlockHash = enc.B58Encode(p.GetBestblock().GetBlockHash()) + out.BestBlock.BlockHash = base58.Encode(p.GetBestblock().GetBlockHash()) out.State = types.PeerState(p.State).String() out.Hidden = p.Hidden out.Self = p.Selfpeer @@ -273,7 +273,7 @@ func ConvPeerLong(p *types.Peer) *LongInOutPeer { out := &LongInOutPeer{InOutPeer: *ConvPeer(p)} out.ProducerIDs = make([]string, len(p.Address.ProducerIDs)) for i, pid := range p.Address.ProducerIDs { - out.ProducerIDs[i] = enc.B58Encode(pid) + out.ProducerIDs[i] = base58.Encode(pid) } if p.Address.Role == types.PeerRole_Agent { out.Certificates = make([]*InOutCert, len(p.Certificates)) @@ -283,7 +283,7 @@ func ConvPeerLong(p *types.Peer) *LongInOutPeer { addrs = append(addrs, string(ad)) } out.Certificates[i] = &InOutCert{CertVersion: cert.CertVersion, - ProducerID: enc.B58Encode(cert.BPID), AgentID: enc.B58Encode(cert.AgentID), + ProducerID: base58.Encode(cert.BPID), AgentID: base58.Encode(cert.AgentID), CreateTime: time.Unix(0, cert.CreateTime), ExpireTime: time.Unix(0, cert.ExpireTime), Addresses: addrs} } @@ -296,10 +296,10 @@ func ConvBlockchainStatus(in *types.BlockchainStatus) string { if in == nil { return "" } - out.Hash = enc.B58Encode(in.BestBlockHash) + out.Hash = base58.Encode(in.BestBlockHash) out.Height = in.BestHeight - out.ChainIdHash = enc.B58Encode(in.BestChainIdHash) + out.ChainIdHash = base58.Encode(in.BestChainIdHash) toJRM := func(s string) *json.RawMessage { if len(s) > 0 { diff --git a/cmd/aergocli/util/base58addr_test.go b/cmd/aergocli/util/base58addr_test.go index 34f37c972..ec6800c28 100644 --- a/cmd/aergocli/util/base58addr_test.go +++ b/cmd/aergocli/util/base58addr_test.go @@ -3,7 +3,7 @@ package util import ( "testing" - "github.com/aergoio/aergo/v2/internal/enc" + "github.com/aergoio/aergo/v2/internal/enc/base58" "github.com/aergoio/aergo/v2/types" "github.com/stretchr/testify/assert" ) @@ -13,8 +13,8 @@ func TestParseConvBase58Tx(t *testing.T) { res, err := ParseBase58Tx([]byte(testjson)) assert.NoError(t, err, "should be success") assert.NotEmpty(t, res, "failed to parse json") - assert.Equal(t, "525mQMtsWaDLVJbzQZgTFkSG33gtZsho7m4io1HUCeJi", enc.B58Encode(res[0].Hash), "wrong hash") - assert.Equal(t, "3tMHYrizQ532D1WJkt5RSs5AcRmq7betw8zvC66Wh3XHUdvNpNzLWh1SkkGYMGJ669nCVuYHrhwfg1HrUUp6KDwzK", enc.B58Encode(res[0].Body.Sign), "wrong sign") + assert.Equal(t, "525mQMtsWaDLVJbzQZgTFkSG33gtZsho7m4io1HUCeJi", base58.Encode(res[0].Hash), "wrong hash") + assert.Equal(t, "3tMHYrizQ532D1WJkt5RSs5AcRmq7betw8zvC66Wh3XHUdvNpNzLWh1SkkGYMGJ669nCVuYHrhwfg1HrUUp6KDwzK", base58.Encode(res[0].Body.Sign), "wrong sign") account, err := types.DecodeAddress("AsiFCzSukVNUGufJSzSNLA1nKx39NxKcVBEWvW3riyfixcBjN1Qd") assert.NoError(t, err, "should be success") @@ -31,8 +31,8 @@ func TestParseBase58TxBody(t *testing.T) { assert.NoError(t, err, "should be success") assert.NotEmpty(t, res, "failed to parse json") - assert.Equal(t, "3roWPzztf5aLLh16vAnd2ugcPux3wJ1oqqvqkWARobjuAC32xftF42nnbTkXUQdkDaFvuUmctrpQSv8FAVUKcywHW", enc.B58Encode(res.Sign), "wrong sign") - assert.Equal(t, "aergo", enc.B58Encode(res.Payload), "wrong payload") + assert.Equal(t, "3roWPzztf5aLLh16vAnd2ugcPux3wJ1oqqvqkWARobjuAC32xftF42nnbTkXUQdkDaFvuUmctrpQSv8FAVUKcywHW", base58.Encode(res.Sign), "wrong sign") + assert.Equal(t, "aergo", base58.Encode(res.Payload), "wrong payload") account, err := types.DecodeAddress("AsiFCzSukVNUGufJSzSNLA1nKx39NxKcVBEWvW3riyfixcBjN1Qd") assert.NoError(t, err, "should be success") assert.Equal(t, account, res.Account, "wrong account") @@ -68,7 +68,7 @@ func TestBlockConvBase58(t *testing.T) { recipient, err := types.DecodeAddress(recipientBase58) assert.NoError(t, err, "should be decode recipient") - payload, err := enc.B58Decode(payloadBase58) + payload, err := base58.Decode(payloadBase58) assert.NoError(t, err, "should be decode payload") testTx := &types.Tx{Body: &types.TxBody{ diff --git a/cmd/aergocli/util/base64ToHex.go b/cmd/aergocli/util/base64ToHex.go index 98d86196d..6ce5d33aa 100644 --- a/cmd/aergocli/util/base64ToHex.go +++ b/cmd/aergocli/util/base64ToHex.go @@ -3,7 +3,7 @@ package util import ( "encoding/json" - "github.com/aergoio/aergo/v2/internal/enc" + "github.com/aergoio/aergo/v2/internal/enc/hex" "github.com/aergoio/aergo/v2/types" ) @@ -18,9 +18,9 @@ type InOutBlockchainStatus struct { func ConvHexBlockchainStatus(in *types.BlockchainStatus) string { out := &InOutBlockchainStatus{} - out.Hash = enc.HexEncode(in.BestBlockHash) + out.Hash = hex.Encode(in.BestBlockHash) out.Height = in.BestHeight - out.ChainIdHash = enc.HexEncode(in.BestChainIdHash) + out.ChainIdHash = hex.Encode(in.BestChainIdHash) jsonout, err := json.Marshal(out) if err != nil { return "" diff --git a/cmd/aergocli/util/encoding/json/decode.go b/cmd/aergocli/util/encoding/json/decode.go index ead4c7157..a6dd2b0d8 100644 --- a/cmd/aergocli/util/encoding/json/decode.go +++ b/cmd/aergocli/util/encoding/json/decode.go @@ -17,7 +17,7 @@ import ( "unicode/utf16" "unicode/utf8" - "github.com/aergoio/aergo/v2/internal/enc" + "github.com/aergoio/aergo/v2/internal/enc/base58" ) // Unmarshal parses the JSON-encoded data and stores the result @@ -934,7 +934,7 @@ func (d *decodeState) literalStore(item []byte, v reflect.Value, fromQuoted bool d.saveError(&UnmarshalTypeError{Value: "string", Type: v.Type(), Offset: int64(d.readIndex())}) break } - b, err := enc.B58Decode(string(s)) + b, err := base58.Decode(string(s)) if err != nil { d.saveError(err) break diff --git a/cmd/aergocli/util/encoding/json/encode.go b/cmd/aergocli/util/encoding/json/encode.go index b5d825124..26b0c472a 100644 --- a/cmd/aergocli/util/encoding/json/encode.go +++ b/cmd/aergocli/util/encoding/json/encode.go @@ -23,7 +23,7 @@ import ( "unicode" "unicode/utf8" - "github.com/aergoio/aergo/v2/internal/enc" + "github.com/aergoio/aergo/v2/internal/enc/base58" ) // Marshal returns the JSON encoding of v. @@ -724,7 +724,7 @@ func encodeByteSlice(e *encodeState, v reflect.Value, _ encOpts) { } s := v.Bytes() e.WriteByte('"') - e.WriteString(enc.B58Encode(s)) + e.WriteString(base58.Encode(s)) e.WriteByte('"') } diff --git a/cmd/aergoluac/encoding/codeEncoding.go b/cmd/aergoluac/encoding/codeEncoding.go index 33c8a6e15..75329ed98 100644 --- a/cmd/aergoluac/encoding/codeEncoding.go +++ b/cmd/aergoluac/encoding/codeEncoding.go @@ -4,22 +4,23 @@ import ( "errors" "fmt" - "github.com/aergoio/aergo/v2/internal/enc" + "github.com/aergoio/aergo/v2/internal/enc/base58check" + "github.com/aergoio/aergo/v2/internal/enc/hex" ) const CodeVersion = 0xC0 func EncodeCode(code []byte) string { - encoded, _ := enc.B58CheckEncode(fmt.Sprintf("%x", CodeVersion), enc.HexEncode(code)) + encoded, _ := base58check.Encode(fmt.Sprintf("%x", CodeVersion), hex.Encode(code)) return encoded } func DecodeCode(encodedCode string) ([]byte, error) { - decodedString, err := enc.B58CheckDecode(encodedCode) + decodedString, err := base58check.Decode(encodedCode) if err != nil { return nil, err } - decodedBytes, err := enc.HexDecode(decodedString) + decodedBytes, err := hex.Decode(decodedString) if err != nil { return nil, err } diff --git a/cmd/aergosvr/init.go b/cmd/aergosvr/init.go index b1396eaae..d9026f177 100644 --- a/cmd/aergosvr/init.go +++ b/cmd/aergosvr/init.go @@ -7,7 +7,7 @@ import ( "github.com/aergoio/aergo/v2/chain" "github.com/aergoio/aergo/v2/consensus/impl" - "github.com/aergoio/aergo/v2/internal/enc" + "github.com/aergoio/aergo/v2/internal/enc/base58" "github.com/aergoio/aergo/v2/types" "github.com/spf13/cobra" ) @@ -36,7 +36,7 @@ var initGenesis = &cobra.Command{ if core != nil { exist := core.GetGenesisInfo() if exist != nil { - fmt.Printf("genesis block(%s) is already initialized\n", enc.B58Encode(exist.Block().GetHash())) + fmt.Printf("genesis block(%s) is already initialized\n", base58.Encode(exist.Block().GetHash())) core.Close() return } @@ -71,7 +71,7 @@ var initGenesis = &cobra.Command{ } g := core.GetGenesisInfo() - fmt.Printf("genesis block[%s] is created in (%s)\n", enc.B58Encode(g.Block().GetHash()), cfg.DataDir) + fmt.Printf("genesis block[%s] is created in (%s)\n", base58.Encode(g.Block().GetHash()), cfg.DataDir) } }, } diff --git a/cmd/colaris/cmd/current.go b/cmd/colaris/cmd/current.go index a53bd07d2..ef96bc018 100644 --- a/cmd/colaris/cmd/current.go +++ b/cmd/colaris/cmd/current.go @@ -10,8 +10,7 @@ import ( "time" "github.com/aergoio/aergo/v2/cmd/aergocli/util" - "github.com/aergoio/aergo/v2/internal/enc" - + "github.com/aergoio/aergo/v2/internal/enc/base58" "github.com/aergoio/aergo/v2/types" "github.com/spf13/cobra" ) @@ -37,7 +36,7 @@ func execCurrentPeers(cmd *cobra.Command, args []string) { var err error if cmd.Flags().Changed("ref") == true { - blockHash, err = enc.B58Decode(cpKey) + blockHash, err = base58.Decode(cpKey) if err != nil { cmd.Printf("Failed: %s", err.Error()) return diff --git a/consensus/chain/block.go b/consensus/chain/block.go index 9067bf501..01b712d22 100644 --- a/consensus/chain/block.go +++ b/consensus/chain/block.go @@ -7,7 +7,7 @@ import ( "time" "github.com/aergoio/aergo/v2/chain" - "github.com/aergoio/aergo/v2/internal/enc" + "github.com/aergoio/aergo/v2/internal/enc/base58" "github.com/aergoio/aergo/v2/message" "github.com/aergoio/aergo/v2/pkg/component" "github.com/aergoio/aergo/v2/state" @@ -124,7 +124,7 @@ func (g *BlockGenerator) Rejected() *RejTxInfo { // SetTimeoutTx set bState.timeoutTx to tx. func (g *BlockGenerator) SetTimeoutTx(tx types.Transaction) { - logger.Warn().Str("hash", enc.B58Encode(tx.GetHash())).Msg("timeout tx marked for eviction") + logger.Warn().Str("hash", base58.Encode(tx.GetHash())).Msg("timeout tx marked for eviction") g.bState.SetTimeoutTx(tx) } @@ -211,7 +211,7 @@ func ConnectBlock(hs component.ICompSyncRequester, block *types.Block, blockStat func SyncChain(hs *component.ComponentHub, targetHash []byte, targetNo types.BlockNo, peerID types.PeerID) error { logger.Info().Stringer("peer", types.LogPeerShort(peerID)).Uint64("no", targetNo). - Str("hash", enc.B58Encode(targetHash)).Msg("request to sync for consensus") + Str("hash", base58.Encode(targetHash)).Msg("request to sync for consensus") notiC := make(chan error) hs.Tell(message.SyncerSvc, &message.SyncStart{PeerID: peerID, TargetNo: targetNo, NotifyC: notiC}) @@ -221,7 +221,7 @@ func SyncChain(hs *component.ComponentHub, targetHash []byte, targetNo types.Blo case err := <-notiC: if err != nil { logger.Error().Err(err).Uint64("no", targetNo). - Str("hash", enc.B58Encode(targetHash)). + Str("hash", base58.Encode(targetHash)). Msg("failed to sync") return err diff --git a/consensus/impl/dpos/blockfactory.go b/consensus/impl/dpos/blockfactory.go index 126497848..3643f2c0c 100644 --- a/consensus/impl/dpos/blockfactory.go +++ b/consensus/impl/dpos/blockfactory.go @@ -19,7 +19,7 @@ import ( "github.com/aergoio/aergo/v2/consensus/impl/dpos/slot" "github.com/aergoio/aergo/v2/contract" "github.com/aergoio/aergo/v2/contract/system" - "github.com/aergoio/aergo/v2/internal/enc" + "github.com/aergoio/aergo/v2/internal/enc/base58" "github.com/aergoio/aergo/v2/p2p/p2pkey" "github.com/aergoio/aergo/v2/pkg/component" "github.com/aergoio/aergo/v2/state" @@ -264,7 +264,7 @@ func (bf *BlockFactory) generateBlock(execCtx context.Context, bpi *bpInfo, lpbN logger.Info(). Str("BP", bf.ID).Str("id", block.ID()). - Str("sroot", enc.B58Encode(block.GetHeader().GetBlocksRootHash())). + Str("sroot", base58.Encode(block.GetHeader().GetBlocksRootHash())). Uint64("no", block.BlockNo()).Uint64("confirms", block.Confirms()). Uint64("lpb", lpbNo). Msg("block produced") @@ -277,7 +277,7 @@ func (bf *BlockFactory) rejected() *chain.RejTxInfo { } func (bf *BlockFactory) setRejected(rej *chain.RejTxInfo) { - logger.Warn().Str("hash", enc.B58Encode(rej.Hash())).Msg("timeout tx reserved for rescheduling") + logger.Warn().Str("hash", base58.Encode(rej.Hash())).Msg("timeout tx reserved for rescheduling") bf.recentRejectedTx = rej } diff --git a/consensus/impl/dpos/bp/cluster.go b/consensus/impl/dpos/bp/cluster.go index 060671299..7a97f2ead 100644 --- a/consensus/impl/dpos/bp/cluster.go +++ b/consensus/impl/dpos/bp/cluster.go @@ -16,7 +16,7 @@ import ( "github.com/aergoio/aergo-lib/log" "github.com/aergoio/aergo/v2/consensus" "github.com/aergoio/aergo/v2/contract/system" - "github.com/aergoio/aergo/v2/internal/enc" + "github.com/aergoio/aergo/v2/internal/enc/gob" "github.com/aergoio/aergo/v2/state" "github.com/aergoio/aergo/v2/types" "github.com/davecgh/go-spew/spew" @@ -287,7 +287,7 @@ func buildKey(blockNo types.BlockNo) []byte { // Value returns s.list. func (s *Snapshot) Value() []byte { - b, err := enc.GobEncode(s.List) + b, err := gob.Encode(s.List) if err != nil { logger.Debug().Err(err).Msg("BP list encoding failed") return nil diff --git a/consensus/impl/dpos/lib.go b/consensus/impl/dpos/lib.go index 41660aa89..c6937a748 100644 --- a/consensus/impl/dpos/lib.go +++ b/consensus/impl/dpos/lib.go @@ -7,7 +7,7 @@ import ( "github.com/aergoio/aergo-lib/db" "github.com/aergoio/aergo/v2/consensus" - "github.com/aergoio/aergo/v2/internal/enc" + "github.com/aergoio/aergo/v2/internal/enc/gob" "github.com/aergoio/aergo/v2/p2p/p2pkey" "github.com/aergoio/aergo/v2/types" "github.com/aergoio/aergo/v2/types/dbkey" @@ -235,7 +235,7 @@ func (ls *libStatus) load(endBlockNo types.BlockNo) { } func (ls *libStatus) save(tx consensus.TxWriter) error { - b, err := enc.GobEncode(ls) + b, err := gob.Encode(ls) if err != nil { return err } @@ -397,7 +397,7 @@ func (bs *bootLoader) decodeStatus(key []byte, dst interface{}) error { return fmt.Errorf("LIB status not found: key = %v", string(key)) } - err := enc.GobDecode(value, dst) + err := gob.Decode(value, dst) if err != nil { logger.Panic().Err(err).Str("key", string(key)). Msg("failed to decode DPoS status") diff --git a/consensus/impl/dpos/lib_test.go b/consensus/impl/dpos/lib_test.go index 9628f2a06..b5c506afd 100644 --- a/consensus/impl/dpos/lib_test.go +++ b/consensus/impl/dpos/lib_test.go @@ -3,7 +3,7 @@ package dpos import ( "testing" - "github.com/aergoio/aergo/v2/internal/enc" + "github.com/aergoio/aergo/v2/internal/enc/base58" "github.com/aergoio/aergo/v2/types" "github.com/libp2p/go-libp2p-core/crypto" "github.com/stretchr/testify/assert" @@ -50,7 +50,7 @@ func newTestChain(clusterSize uint16) (*testChain, error) { tc := &testChain{ chain: make([]*types.Block, 0), status: NewStatus(&testCluster{size: clusterSize}, nil, nil, 0), - bpid: enc.B58Encode(b), + bpid: base58.Encode(b), lpb: make(map[string]types.BlockNo), bpKey: bpKey, bpClusterSize: clusterSize, @@ -78,7 +78,7 @@ func (tc *testChain) addBlock(i types.BlockNo) error { if err != nil { return err } - spk := enc.B58Encode(b) + spk := base58.Encode(b) prevBlock := tc.chain[len(tc.chain)-1] block := newBlockFromPrev(prevBlock, 0, types.DummyBlockVersionner(0)) diff --git a/consensus/impl/raftv2/blockfactory.go b/consensus/impl/raftv2/blockfactory.go index 661cb48ac..5aa478851 100644 --- a/consensus/impl/raftv2/blockfactory.go +++ b/consensus/impl/raftv2/blockfactory.go @@ -19,7 +19,7 @@ import ( "github.com/aergoio/aergo/v2/consensus/chain" "github.com/aergoio/aergo/v2/contract" "github.com/aergoio/aergo/v2/contract/system" - "github.com/aergoio/aergo/v2/internal/enc" + "github.com/aergoio/aergo/v2/internal/enc/base58" "github.com/aergoio/aergo/v2/p2p/p2pcommon" "github.com/aergoio/aergo/v2/p2p/p2pkey" "github.com/aergoio/aergo/v2/pkg/component" @@ -541,7 +541,7 @@ func (bf *BlockFactory) generateBlock(work *Work) (*types.Block, *state.BlockSta } logger.Info().Str("blockProducer", bf.ID).Str("raftID", EtcdIDToString(bf.bpc.NodeID())). - Str("sroot", enc.B58Encode(block.GetHeader().GetBlocksRootHash())). + Str("sroot", base58.Encode(block.GetHeader().GetBlocksRootHash())). Uint64("no", block.GetHeader().GetBlockNo()). Str("hash", block.ID()). Msg("block produced") diff --git a/consensus/impl/raftv2/cluster.go b/consensus/impl/raftv2/cluster.go index 18ea2284e..21b68c6b2 100644 --- a/consensus/impl/raftv2/cluster.go +++ b/consensus/impl/raftv2/cluster.go @@ -14,7 +14,7 @@ import ( "github.com/aergoio/aergo/v2/cmd/aergocli/util" "github.com/aergoio/aergo/v2/consensus" - "github.com/aergoio/aergo/v2/internal/enc" + "github.com/aergoio/aergo/v2/internal/enc/base58" "github.com/aergoio/aergo/v2/message" "github.com/aergoio/aergo/v2/pkg/component" "github.com/aergoio/aergo/v2/types" @@ -409,7 +409,7 @@ func (cl *Cluster) isValidMember(member *consensus.Member) error { } // check if peerID of this node is valid - if cl.NodeName() == member.Name && enc.B58Encode([]byte(member.GetPeerID())) != cl.NodePeerID() { + if cl.NodeName() == member.Name && base58.Encode([]byte(member.GetPeerID())) != cl.NodePeerID() { logger.Error().Str("config", member.GetPeerID().String()).Str("cluster peerid", cl.NodePeerID()).Msg("peerID value is not matched with P2P") return ErrInvalidRaftPeerID } @@ -433,7 +433,7 @@ func (cl *Cluster) addMember(member *consensus.Member, applied bool) error { // notify to p2p TODO temporary code peerID, err := types.IDFromBytes(member.PeerID) if err != nil { - logger.Panic().Err(err).Str("peerid", enc.B58Encode(member.PeerID)).Msg("invalid member peerid") + logger.Panic().Err(err).Str("peerid", base58.Encode(member.PeerID)).Msg("invalid member peerid") } if cl.notifyFn != nil { @@ -466,7 +466,7 @@ func (cl *Cluster) removeMember(member *consensus.Member) error { // notify to p2p TODO temporary code peerID, err := types.IDFromBytes(member.PeerID) if err != nil { - logger.Panic().Err(err).Str("peerid", enc.B58Encode(member.PeerID)).Msg("invalid member peerid") + logger.Panic().Err(err).Str("peerid", base58.Encode(member.PeerID)).Msg("invalid member peerid") } if cl.notifyFn != nil { @@ -494,7 +494,7 @@ func (cl *Cluster) ValidateAndMergeExistingCluster(existingCl *Cluster) bool { } // TODO check my network config is equal to member of remote - if enc.B58Encode(remoteMember.PeerID) != cl.NodePeerID() { + if base58.Encode(remoteMember.PeerID) != cl.NodePeerID() { logger.Error().Msg("peerid is different with peerid of member of existing cluster") } diff --git a/consensus/impl/sbp/sbp.go b/consensus/impl/sbp/sbp.go index 1d4bf92d5..47f3f5bae 100644 --- a/consensus/impl/sbp/sbp.go +++ b/consensus/impl/sbp/sbp.go @@ -12,7 +12,7 @@ import ( "github.com/aergoio/aergo/v2/consensus/chain" "github.com/aergoio/aergo/v2/contract" "github.com/aergoio/aergo/v2/contract/system" - "github.com/aergoio/aergo/v2/internal/enc" + "github.com/aergoio/aergo/v2/internal/enc/base58" "github.com/aergoio/aergo/v2/pkg/component" "github.com/aergoio/aergo/v2/state" "github.com/aergoio/aergo/v2/types" @@ -202,7 +202,7 @@ func (s *SimpleBlockFactory) Start() { continue } logger.Info().Uint64("no", block.GetHeader().GetBlockNo()).Str("hash", block.ID()). - Str("TrieRoot", enc.B58Encode(block.GetHeader().GetBlocksRootHash())). + Str("TrieRoot", base58.Encode(block.GetHeader().GetBlocksRootHash())). Err(err).Msg("block produced") chain.ConnectBlock(s, block, blockState, time.Second) diff --git a/consensus/raftCommon.go b/consensus/raftCommon.go index 30216420b..eefd26d5b 100644 --- a/consensus/raftCommon.go +++ b/consensus/raftCommon.go @@ -10,7 +10,8 @@ import ( "fmt" "io" - "github.com/aergoio/aergo/v2/internal/enc" + "github.com/aergoio/aergo/v2/internal/enc/base58" + "github.com/aergoio/aergo/v2/internal/enc/gob" "github.com/aergoio/aergo/v2/types" "github.com/aergoio/etcd/raft" "github.com/aergoio/etcd/raft/raftpb" @@ -58,7 +59,7 @@ type WalEntry struct { } func (we *WalEntry) ToBytes() ([]byte, error) { - return enc.GobEncode(we) + return gob.Encode(we) } func (we *WalEntry) ToString() string { @@ -196,7 +197,7 @@ func (csnap *ChainSnapshot) ToString() string { if csnap == nil || csnap.Hash == nil { return "csnap: empty" } - return fmt.Sprintf("chainsnap:(no=%d, hash=%s)", csnap.No, enc.B58Encode(csnap.Hash)) + return fmt.Sprintf("chainsnap:(no=%d, hash=%s)", csnap.No, base58.Encode(csnap.Hash)) } /* diff --git a/contract/contract_test.go b/contract/contract_test.go index 2689a32f6..46ff3c732 100644 --- a/contract/contract_test.go +++ b/contract/contract_test.go @@ -114,34 +114,34 @@ func TestCheckExecution(t *testing.T) { isDeploy bool isContract bool - expectErr error + expectErr error expectExec bool }{ // deploy - {version:2, txType:types.TxType_NORMAL, amount:types.NewAmount(1,types.Aergo), payloadSize:1000, isDeploy:true, isContract:false, expectErr:nil, expectExec:true}, - {version:2, txType:types.TxType_DEPLOY, amount:types.NewAmount(1,types.Aergo), payloadSize:1000, isDeploy:true, isContract:false, expectErr:nil, expectExec:true}, - {version:2, txType:types.TxType_REDEPLOY, amount:types.NewAmount(1,types.Aergo), payloadSize:1000, isDeploy:true, isContract:false, expectErr:nil, expectExec:true}, - {version:3, txType:types.TxType_NORMAL, amount:types.NewAmount(1,types.Aergo), payloadSize:1000, isDeploy:true, isContract:false, expectErr:nil, expectExec:true}, - {version:3, txType:types.TxType_DEPLOY, amount:types.NewAmount(1,types.Aergo), payloadSize:1000, isDeploy:true, isContract:false, expectErr:nil, expectExec:true}, - {version:3, txType:types.TxType_REDEPLOY, amount:types.NewAmount(1,types.Aergo), payloadSize:1000, isDeploy:true, isContract:false, expectErr:nil, expectExec:true}, + {version: 2, txType: types.TxType_NORMAL, amount: types.NewAmount(1, types.Aergo), payloadSize: 1000, isDeploy: true, isContract: false, expectErr: nil, expectExec: true}, + {version: 2, txType: types.TxType_DEPLOY, amount: types.NewAmount(1, types.Aergo), payloadSize: 1000, isDeploy: true, isContract: false, expectErr: nil, expectExec: true}, + {version: 2, txType: types.TxType_REDEPLOY, amount: types.NewAmount(1, types.Aergo), payloadSize: 1000, isDeploy: true, isContract: false, expectErr: nil, expectExec: true}, + {version: 3, txType: types.TxType_NORMAL, amount: types.NewAmount(1, types.Aergo), payloadSize: 1000, isDeploy: true, isContract: false, expectErr: nil, expectExec: true}, + {version: 3, txType: types.TxType_DEPLOY, amount: types.NewAmount(1, types.Aergo), payloadSize: 1000, isDeploy: true, isContract: false, expectErr: nil, expectExec: true}, + {version: 3, txType: types.TxType_REDEPLOY, amount: types.NewAmount(1, types.Aergo), payloadSize: 1000, isDeploy: true, isContract: false, expectErr: nil, expectExec: true}, // recipient is contract - {version:2, txType:types.TxType_NORMAL, amount:types.NewAmount(1,types.Aergo), payloadSize:1000, isDeploy:false, isContract:true, expectErr:nil, expectExec:true}, - {version:2, txType:types.TxType_TRANSFER, amount:types.NewAmount(1,types.Aergo), payloadSize:1000, isDeploy:false, isContract:true, expectErr:nil, expectExec:true}, - {version:2, txType:types.TxType_CALL, amount:types.NewAmount(1,types.Aergo), payloadSize:1000, isDeploy:false, isContract:true, expectErr:nil, expectExec:true}, - {version:2, txType:types.TxType_FEEDELEGATION, amount:types.NewAmount(1,types.Aergo), payloadSize:1000, isDeploy:false, isContract:true, expectErr:nil, expectExec:true}, - {version:3, txType:types.TxType_NORMAL, amount:types.NewAmount(1,types.Aergo), payloadSize:1000, isDeploy:false, isContract:true, expectErr:nil, expectExec:true}, - {version:3, txType:types.TxType_TRANSFER, amount:types.NewAmount(1,types.Aergo), payloadSize:1000, isDeploy:false, isContract:true, expectErr:nil, expectExec:true}, - {version:3, txType:types.TxType_CALL, amount:types.NewAmount(1,types.Aergo), payloadSize:1000, isDeploy:false, isContract:true, expectErr:nil, expectExec:true}, - {version:3, txType:types.TxType_FEEDELEGATION, amount:types.NewAmount(1,types.Aergo), payloadSize:1000, isDeploy:false, isContract:true, expectErr:nil, expectExec:true}, + {version: 2, txType: types.TxType_NORMAL, amount: types.NewAmount(1, types.Aergo), payloadSize: 1000, isDeploy: false, isContract: true, expectErr: nil, expectExec: true}, + {version: 2, txType: types.TxType_TRANSFER, amount: types.NewAmount(1, types.Aergo), payloadSize: 1000, isDeploy: false, isContract: true, expectErr: nil, expectExec: true}, + {version: 2, txType: types.TxType_CALL, amount: types.NewAmount(1, types.Aergo), payloadSize: 1000, isDeploy: false, isContract: true, expectErr: nil, expectExec: true}, + {version: 2, txType: types.TxType_FEEDELEGATION, amount: types.NewAmount(1, types.Aergo), payloadSize: 1000, isDeploy: false, isContract: true, expectErr: nil, expectExec: true}, + {version: 3, txType: types.TxType_NORMAL, amount: types.NewAmount(1, types.Aergo), payloadSize: 1000, isDeploy: false, isContract: true, expectErr: nil, expectExec: true}, + {version: 3, txType: types.TxType_TRANSFER, amount: types.NewAmount(1, types.Aergo), payloadSize: 1000, isDeploy: false, isContract: true, expectErr: nil, expectExec: true}, + {version: 3, txType: types.TxType_CALL, amount: types.NewAmount(1, types.Aergo), payloadSize: 1000, isDeploy: false, isContract: true, expectErr: nil, expectExec: true}, + {version: 3, txType: types.TxType_FEEDELEGATION, amount: types.NewAmount(1, types.Aergo), payloadSize: 1000, isDeploy: false, isContract: true, expectErr: nil, expectExec: true}, // recipient is not a contract - {version:2, txType:types.TxType_NORMAL, amount:types.NewAmount(1,types.Aergo), payloadSize:1000, isDeploy:false, isContract:false, expectErr:nil, expectExec:false}, - {version:2, txType:types.TxType_TRANSFER, amount:types.NewAmount(1,types.Aergo), payloadSize:1000, isDeploy:false, isContract:false, expectErr:nil, expectExec:false}, - {version:2, txType:types.TxType_CALL, amount:types.NewAmount(1,types.Aergo), payloadSize:1000, isDeploy:false, isContract:false, expectErr:nil, expectExec:false}, - {version:2, txType:types.TxType_FEEDELEGATION, amount:types.NewAmount(1,types.Aergo), payloadSize:1000, isDeploy:false, isContract:false, expectErr:nil, expectExec:false}, - {version:3, txType:types.TxType_NORMAL, amount:types.NewAmount(1,types.Aergo), payloadSize:1000, isDeploy:false, isContract:false, expectErr:nil, expectExec:false}, - {version:3, txType:types.TxType_TRANSFER, amount:types.NewAmount(1,types.Aergo), payloadSize:1000, isDeploy:false, isContract:false, expectErr:nil, expectExec:false}, - {version:3, txType:types.TxType_CALL, amount:types.NewAmount(1,types.Aergo), payloadSize:1000, isDeploy:false, isContract:false, expectErr:nil, expectExec:true}, - {version:3, txType:types.TxType_FEEDELEGATION, amount:types.NewAmount(1,types.Aergo), payloadSize:1000, isDeploy:false, isContract:false, expectErr:nil, expectExec:false}, + {version: 2, txType: types.TxType_NORMAL, amount: types.NewAmount(1, types.Aergo), payloadSize: 1000, isDeploy: false, isContract: false, expectErr: nil, expectExec: false}, + {version: 2, txType: types.TxType_TRANSFER, amount: types.NewAmount(1, types.Aergo), payloadSize: 1000, isDeploy: false, isContract: false, expectErr: nil, expectExec: false}, + {version: 2, txType: types.TxType_CALL, amount: types.NewAmount(1, types.Aergo), payloadSize: 1000, isDeploy: false, isContract: false, expectErr: nil, expectExec: false}, + {version: 2, txType: types.TxType_FEEDELEGATION, amount: types.NewAmount(1, types.Aergo), payloadSize: 1000, isDeploy: false, isContract: false, expectErr: nil, expectExec: false}, + {version: 3, txType: types.TxType_NORMAL, amount: types.NewAmount(1, types.Aergo), payloadSize: 1000, isDeploy: false, isContract: false, expectErr: nil, expectExec: false}, + {version: 3, txType: types.TxType_TRANSFER, amount: types.NewAmount(1, types.Aergo), payloadSize: 1000, isDeploy: false, isContract: false, expectErr: nil, expectExec: false}, + {version: 3, txType: types.TxType_CALL, amount: types.NewAmount(1, types.Aergo), payloadSize: 1000, isDeploy: false, isContract: false, expectErr: nil, expectExec: true}, + {version: 3, txType: types.TxType_FEEDELEGATION, amount: types.NewAmount(1, types.Aergo), payloadSize: 1000, isDeploy: false, isContract: false, expectErr: nil, expectExec: false}, } { do_execute, err := checkExecution(test.txType, test.amount, test.payloadSize, test.version, test.isDeploy, test.isContract) assert.Equal(t, test.expectErr, err, "checkExecution(version:%d, txType:%d, amount:%s, payloadSize:%d)", test.version, test.txType, test.amount, test.payloadSize) diff --git a/contract/enterprise/validate.go b/contract/enterprise/validate.go index 0d8b3ba05..9001362f0 100644 --- a/contract/enterprise/validate.go +++ b/contract/enterprise/validate.go @@ -8,7 +8,7 @@ import ( "strings" "github.com/aergoio/aergo/v2/consensus" - "github.com/aergoio/aergo/v2/internal/enc" + "github.com/aergoio/aergo/v2/internal/enc/base64" "github.com/aergoio/aergo/v2/state" "github.com/aergoio/aergo/v2/types" ) @@ -265,7 +265,7 @@ func checkRPCPermissions(v string) error { return fmt.Errorf("invalid RPC permission %s", v) } - if _, err := enc.B64Decode(values[0]); err != nil { + if _, err := base64.Decode(values[0]); err != nil { return fmt.Errorf("invalid RPC cert %s", v) } diff --git a/contract/ethstorageproof.go b/contract/ethstorageproof.go index fde576689..018c8e9a1 100644 --- a/contract/ethstorageproof.go +++ b/contract/ethstorageproof.go @@ -6,7 +6,7 @@ import ( "errors" "math" - "github.com/aergoio/aergo/v2/internal/enc" + "github.com/aergoio/aergo/v2/internal/enc/hex" "golang.org/x/crypto/sha3" ) @@ -33,7 +33,7 @@ func verifyEthStorageProof(key []byte, value rlpObject, expectedHash []byte, pro if len(key) == 0 || value == nil || len(proof) == 0 { return false } - key = []byte(enc.HexEncode(keccak256(key))) + key = []byte(hex.Encode(keccak256(key))) valueRlpEncoded := rlpEncode(value) ks := keyStream{bytes.NewBuffer(key)} for i, p := range proof { @@ -50,7 +50,7 @@ func verifyEthStorageProof(key []byte, value rlpObject, expectedHash []byte, pro if err != nil { return false } - sharedNibbles = append(sharedNibbles, []byte(enc.HexEncode(n[0][1:]))...) + sharedNibbles = append(sharedNibbles, []byte(hex.Encode(n[0][1:]))...) if len(sharedNibbles) == 0 { return false } @@ -180,7 +180,7 @@ func keccak256(data ...[]byte) []byte { } func keccak256Hex(data ...[]byte) string { - return enc.HexEncode(keccak256(data...)) + return hex.Encode(keccak256(data...)) } func decodeHpHeader(b byte) (bool, []byte, error) { diff --git a/contract/ethstorageproof_test.go b/contract/ethstorageproof_test.go index b00e24919..9da60d342 100644 --- a/contract/ethstorageproof_test.go +++ b/contract/ethstorageproof_test.go @@ -6,7 +6,7 @@ import ( "reflect" "testing" - "github.com/aergoio/aergo/v2/internal/enc" + "github.com/aergoio/aergo/v2/internal/enc/hex" ) func TestVerify(t *testing.T) { @@ -206,14 +206,14 @@ func removeHexPrefix(s string) string { } func toBytes(s string) []byte { - n, _ := enc.HexDecode(removeHexPrefix(s)) + n, _ := hex.Decode(removeHexPrefix(s)) return n } func proofToBytes(proof []string) [][]byte { var r [][]byte for _, n := range proof { - d, err := enc.HexDecode(removeHexPrefix(n)) + d, err := hex.Decode(removeHexPrefix(n)) if err != nil { return [][]byte{} } diff --git a/contract/hook_dbg.go b/contract/hook_dbg.go index d1ce0ae75..72fba8aba 100644 --- a/contract/hook_dbg.go +++ b/contract/hook_dbg.go @@ -14,7 +14,7 @@ import ( "fmt" "path/filepath" - "github.com/aergoio/aergo/v2/internal/enc" + "github.com/aergoio/aergo/v2/internal/enc/hex" "github.com/aergoio/aergo/v2/types" ) @@ -43,7 +43,7 @@ func (ce *executor) setCountHook(limit C.int) { } func HexAddrToBase58Addr(contract_id_hex string) (string, error) { - byteContractID, err := enc.HexDecode(contract_id_hex) + byteContractID, err := hex.Decode(contract_id_hex) if err != nil { return "", err } @@ -66,7 +66,7 @@ func HexAddrOrPlainStrToHexAddr(d string) string { } func PlainStrToHexAddr(d string) string { - return enc.HexEncode(StrHash(d)) + return hex.Encode(StrHash(d)) } func SetBreakPoint(contract_id_hex string, line uint64) error { diff --git a/contract/statesql.go b/contract/statesql.go index 4f4fe69cf..06c0ff14a 100644 --- a/contract/statesql.go +++ b/contract/statesql.go @@ -15,7 +15,7 @@ import ( "sync" "github.com/aergoio/aergo-lib/log" - "github.com/aergoio/aergo/v2/internal/enc" + "github.com/aergoio/aergo/v2/internal/enc/base58" "github.com/aergoio/aergo/v2/state" "github.com/aergoio/aergo/v2/types" ) @@ -49,7 +49,7 @@ func init() { sql.Register(statesqlDriver, &SQLiteDriver{ ConnectHook: func(conn *SQLiteConn) error { if _, ok := database.DBs[database.OpenDbName]; !ok { - b, err := enc.B58Decode(database.OpenDbName) + b, err := base58.Decode(database.OpenDbName) if err != nil { sqlLgr.Error().Err(err).Msg("Open SQL Connection") return nil diff --git a/contract/system/execute.go b/contract/system/execute.go index 5975988ab..a785ac674 100644 --- a/contract/system/execute.go +++ b/contract/system/execute.go @@ -10,7 +10,7 @@ import ( "fmt" "math/big" - "github.com/aergoio/aergo/v2/internal/enc" + "github.com/aergoio/aergo/v2/internal/enc/base58" "github.com/aergoio/aergo/v2/state" "github.com/aergoio/aergo/v2/types" ) @@ -115,7 +115,7 @@ func GetVotes(scs *state.ContractState, address []byte) ([]*types.VoteInfo, erro if bytes.Equal(key, defaultVoteKey) { for offset := 0; offset < len(v.Candidate); offset += PeerIDLength { - candi := enc.B58Encode(v.Candidate[offset : offset+PeerIDLength]) + candi := base58.Encode(v.Candidate[offset : offset+PeerIDLength]) result.Candidates = append(result.Candidates, candi) } } else { diff --git a/contract/system/execute_test.go b/contract/system/execute_test.go index 4bf2d5a42..479c75951 100644 --- a/contract/system/execute_test.go +++ b/contract/system/execute_test.go @@ -9,7 +9,7 @@ import ( "testing" "github.com/aergoio/aergo/v2/config" - "github.com/aergoio/aergo/v2/internal/enc" + "github.com/aergoio/aergo/v2/internal/enc/base58" "github.com/aergoio/aergo/v2/types" "github.com/stretchr/testify/assert" ) @@ -310,7 +310,7 @@ func TestValidateSystemTxForVoting(t *testing.T) { defer deinitTest() const testSender = "AmPNYHyzyh9zweLwDyuoiUuTVCdrdksxkRWDjVJS76WQLExa2Jr4" const testCandidate = "16Uiu2HAmUJhjwotQqm7eGyZh1ZHrVviQJrdm2roQouD329vxZEkx" - candidates, err := enc.B58Decode(testCandidate) + candidates, err := base58.Decode(testCandidate) assert.NoError(t, err, "could not decode candidates") account, err := types.DecodeAddress(testSender) diff --git a/contract/system/vote.go b/contract/system/vote.go index 63163a54b..afee0a0ac 100644 --- a/contract/system/vote.go +++ b/contract/system/vote.go @@ -12,7 +12,7 @@ import ( "math/big" "strings" - "github.com/aergoio/aergo/v2/internal/enc" + "github.com/aergoio/aergo/v2/internal/enc/base58" "github.com/aergoio/aergo/v2/state" "github.com/aergoio/aergo/v2/types" "github.com/aergoio/aergo/v2/types/dbkey" @@ -144,7 +144,7 @@ func newVoteCmd(ctx *SystemContext) (sysCmd, error) { return nil, err } for _, v := range ctx.Call.Args { - candidate, _ := enc.B58Decode(v.(string)) + candidate, _ := base58.Decode(v.(string)) cmd.candidate = append(cmd.candidate, candidate...) } } @@ -322,7 +322,7 @@ func BuildOrderedCandidates(vote map[string]*big.Int) []string { l := voteResult.buildVoteList() bps := make([]string, 0, len(l.Votes)) for _, v := range l.Votes { - bp := enc.B58Encode(v.Candidate) + bp := base58.Encode(v.Candidate) bps = append(bps, bp) } return bps @@ -356,7 +356,7 @@ func GetRankers(ar AccountStateReader) ([]string, error) { bps := make([]string, 0, n) for _, v := range vl.Votes { - bps = append(bps, enc.B58Encode(v.Candidate)) + bps = append(bps, base58.Encode(v.Candidate)) } return bps, nil } diff --git a/contract/system/vote_test.go b/contract/system/vote_test.go index ef8cad4b5..0d8bb233b 100644 --- a/contract/system/vote_test.go +++ b/contract/system/vote_test.go @@ -14,7 +14,7 @@ import ( "testing" "github.com/aergoio/aergo-lib/db" - "github.com/aergoio/aergo/v2/internal/enc" + "github.com/aergoio/aergo/v2/internal/enc/base58" "github.com/aergoio/aergo/v2/state" "github.com/aergoio/aergo/v2/types" "github.com/libp2p/go-libp2p-core/crypto" @@ -82,7 +82,7 @@ func TestVoteResult(t *testing.T) { testResult := map[string]*big.Int{} for i := 0; i < testSize; i++ { to := fmt.Sprintf("%39d", i) //39:peer id length - testResult[enc.B58Encode([]byte(to))] = new(big.Int).SetUint64(uint64(i * i)) + testResult[base58.Encode([]byte(to))] = new(big.Int).SetUint64(uint64(i * i)) } err = InitVoteResult(scs, nil) assert.NotNil(t, err, "argument should not be nil") @@ -166,7 +166,7 @@ func TestBasicStakingVotingUnstaking(t *testing.T) { result, err := getVoteResult(scs, defaultVoteKey, 23) assert.NoError(t, err, "voting failed") assert.EqualValues(t, len(result.GetVotes()), 1, "invalid voting result") - assert.Equal(t, voting.arg(0), enc.B58Encode(result.GetVotes()[0].Candidate), "invalid candidate in voting result") + assert.Equal(t, voting.arg(0), base58.Encode(result.GetVotes()[0].Candidate), "invalid candidate in voting result") assert.Equal(t, types.StakingMinimum.Bytes(), result.GetVotes()[0].Amount, "invalid amount in voting result") tx.Body.Payload = buildStakingPayload(false) @@ -224,7 +224,7 @@ func buildVotingPayload(count int) []byte { for i := 0; i < count; i++ { peerID := make([]byte, PeerIDLength) peerID[0] = byte(i) - ci.Args = append(ci.Args, enc.B58Encode(peerID)) + ci.Args = append(ci.Args, base58.Encode(peerID)) } payload, _ := json.Marshal(ci) return payload diff --git a/contract/system/voteresult.go b/contract/system/voteresult.go index f9247be7c..386726de9 100644 --- a/contract/system/voteresult.go +++ b/contract/system/voteresult.go @@ -8,7 +8,7 @@ import ( "math/big" "sort" - "github.com/aergoio/aergo/v2/internal/enc" + "github.com/aergoio/aergo/v2/internal/enc/base58" "github.com/aergoio/aergo/v2/state" "github.com/aergoio/aergo/v2/types" "github.com/aergoio/aergo/v2/types/dbkey" @@ -56,7 +56,7 @@ func (voteResult *VoteResult) SubVote(vote *types.Vote) error { } else { for offset := 0; offset < len(vote.Candidate); offset += PeerIDLength { peer := vote.Candidate[offset : offset+PeerIDLength] - pkey := enc.B58Encode(peer) + pkey := base58.Encode(peer) voteResult.rmap[pkey] = new(big.Int).Sub(voteResult.rmap[pkey], vote.GetAmountBigInt()) } } @@ -80,10 +80,10 @@ func (voteResult *VoteResult) AddVote(vote *types.Vote) error { } else { for offset := 0; offset < len(vote.Candidate); offset += PeerIDLength { key := vote.Candidate[offset : offset+PeerIDLength] - if voteResult.rmap[enc.B58Encode(key)] == nil { - voteResult.rmap[enc.B58Encode(key)] = new(big.Int).SetUint64(0) + if voteResult.rmap[base58.Encode(key)] == nil { + voteResult.rmap[base58.Encode(key)] = new(big.Int).SetUint64(0) } - voteResult.rmap[enc.B58Encode(key)] = new(big.Int).Add(voteResult.rmap[enc.B58Encode(key)], vote.GetAmountBigInt()) + voteResult.rmap[base58.Encode(key)] = new(big.Int).Add(voteResult.rmap[base58.Encode(key)], vote.GetAmountBigInt()) } } return nil @@ -98,7 +98,7 @@ func (vr *VoteResult) buildVoteList() *types.VoteList { if vr.ex { vote.Candidate = []byte(k) } else { - vote.Candidate, _ = enc.B58Decode(k) + vote.Candidate, _ = base58.Decode(k) } voteList.Votes = append(voteList.Votes, vote) } @@ -159,7 +159,7 @@ func loadVoteResult(scs *state.ContractState, key []byte) (*VoteResult, error) { if voteResult.ex { voteResult.rmap[string(v.Candidate)] = v.GetAmountBigInt() } else { - voteResult.rmap[enc.B58Encode(v.Candidate)] = v.GetAmountBigInt() + voteResult.rmap[base58.Encode(v.Candidate)] = v.GetAmountBigInt() } } } diff --git a/contract/system/vprt.go b/contract/system/vprt.go index aa6d645bc..0a4eadacb 100644 --- a/contract/system/vprt.go +++ b/contract/system/vprt.go @@ -12,7 +12,7 @@ import ( "reflect" "github.com/aergoio/aergo-lib/log" - "github.com/aergoio/aergo/v2/internal/enc" + "github.com/aergoio/aergo/v2/internal/enc/base58" "github.com/aergoio/aergo/v2/state" "github.com/aergoio/aergo/v2/types" "github.com/aergoio/aergo/v2/types/dbkey" @@ -611,7 +611,7 @@ func (v *vpr) add(id types.AccountID, addr []byte, power *big.Int) { if vprLogger.IsDebugEnabled() { vprLogger.Debug(). Str("op", "add"). - Str("addr", enc.B58Encode(addr)). + Str("addr", base58.Encode(addr)). Str("orig", lhs.String()). Str("delta", power.String()). Msg("prepare voting power change") @@ -631,7 +631,7 @@ func (v *vpr) sub(id types.AccountID, addr []byte, power *big.Int) { if vprLogger.IsDebugEnabled() { vprLogger.Debug(). Str("op", "sub"). - Str("addr", enc.B58Encode(addr)). + Str("addr", base58.Encode(addr)). Str("orig", lhs.String()). Str("delta", power.String()). Msg("prepare voting power change") @@ -710,7 +710,7 @@ func (v *vpr) pickVotingRewardWinner(seed int64) (types.Address, error) { if vprLogger.IsDebugEnabled() { vprLogger.Debug(). Str("total voting power", totalVp.String()). - Str("addr", enc.B58Encode(winner)). + Str("addr", base58.Encode(winner)). Msg("pick voting reward winner") } diff --git a/contract/system/vprt_test.go b/contract/system/vprt_test.go index 80652c2f0..ee418bc16 100644 --- a/contract/system/vprt_test.go +++ b/contract/system/vprt_test.go @@ -11,7 +11,7 @@ import ( "github.com/aergoio/aergo-lib/db" "github.com/aergoio/aergo-lib/log" - "github.com/aergoio/aergo/v2/internal/enc" + "github.com/aergoio/aergo/v2/internal/enc/base58" "github.com/aergoio/aergo/v2/state" "github.com/aergoio/aergo/v2/types" "github.com/stretchr/testify/assert" @@ -176,8 +176,8 @@ func openSystemAccount(t *testing.T) *state.ContractState { assert.NoError(t, err, "fail to open the system contract state") logger.Debug().Msgf( "(after) state, contract: %s, %s\n", - enc.B58Encode(vprStateDB.GetRoot()), - enc.B58Encode(s.GetStorageRoot())) + base58.Encode(vprStateDB.GetRoot()), + base58.Encode(s.GetStorageRoot())) return s } diff --git a/contract/vm.go b/contract/vm.go index d4e74492f..ad669675f 100644 --- a/contract/vm.go +++ b/contract/vm.go @@ -38,7 +38,8 @@ import ( "github.com/aergoio/aergo-lib/log" luacUtil "github.com/aergoio/aergo/v2/cmd/aergoluac/util" "github.com/aergoio/aergo/v2/fee" - "github.com/aergoio/aergo/v2/internal/enc" + "github.com/aergoio/aergo/v2/internal/enc/base58" + "github.com/aergoio/aergo/v2/internal/enc/hex" "github.com/aergoio/aergo/v2/state" "github.com/aergoio/aergo/v2/types" "github.com/aergoio/aergo/v2/types/dbkey" @@ -173,7 +174,7 @@ func newContractInfo(cs *callState, sender, contractId []byte, rp uint64, amount func getTraceFile(blkno uint64, tx []byte) *os.File { f, _ := os.OpenFile(fmt.Sprintf("%s%s%d.trace", os.TempDir(), string(os.PathSeparator), blkno), os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0644) if f != nil { - _, _ = f.WriteString(fmt.Sprintf("[START TX]: %s\n", enc.B58Encode(tx))) + _, _ = f.WriteString(fmt.Sprintf("[START TX]: %s\n", base58.Encode(tx))) } return f } @@ -913,8 +914,8 @@ func setRandomSeed(ctx *vmContext) { if ctx.isQuery { randSrc = rand.NewSource(ctx.blockInfo.Ts) } else { - b, _ := new(big.Int).SetString(enc.B58Encode(ctx.blockInfo.PrevBlockHash[:7]), 62) - t, _ := new(big.Int).SetString(enc.B58Encode(ctx.txHash[:7]), 62) + b, _ := new(big.Int).SetString(base58.Encode(ctx.blockInfo.PrevBlockHash[:7]), 62) + t, _ := new(big.Int).SetString(base58.Encode(ctx.txHash[:7]), 62) b.Add(b, t) randSrc = rand.NewSource(b.Int64()) } @@ -1458,7 +1459,7 @@ func (ce *executor) vmLoadCode(id []byte) { if ce.ctx.blockInfo.ForkVersion >= 3 { chunkId = C.CString("@" + types.EncodeAddress(id)) } else { - chunkId = C.CString(enc.HexEncode(id)) + chunkId = C.CString(hex.Encode(id)) } defer C.free(unsafe.Pointer(chunkId)) if cErrMsg := C.vm_loadbuff( diff --git a/contract/vm_callback.go b/contract/vm_callback.go index dd4b73fca..7613a960d 100644 --- a/contract/vm_callback.go +++ b/contract/vm_callback.go @@ -38,7 +38,8 @@ import ( "github.com/aergoio/aergo/v2/contract/name" "github.com/aergoio/aergo/v2/contract/system" "github.com/aergoio/aergo/v2/internal/common" - "github.com/aergoio/aergo/v2/internal/enc" + "github.com/aergoio/aergo/v2/internal/enc/base58" + "github.com/aergoio/aergo/v2/internal/enc/hex" "github.com/aergoio/aergo/v2/state" "github.com/aergoio/aergo/v2/types" "github.com/aergoio/aergo/v2/types/dbkey" @@ -784,7 +785,7 @@ func luaGetSender(L *LState, service C.int) *C.char { //export luaGetHash func luaGetHash(L *LState, service C.int) *C.char { ctx := contexts[service] - return C.CString(enc.B58Encode(ctx.txHash)) + return C.CString(base58.Encode(ctx.txHash)) } //export luaGetBlockNo @@ -822,7 +823,7 @@ func luaGetOrigin(L *LState, service C.int) *C.char { //export luaGetPrevBlockHash func luaGetPrevBlockHash(L *LState, service C.int) *C.char { ctx := contexts[service] - return C.CString(enc.B58Encode(ctx.blockInfo.PrevBlockHash)) + return C.CString(base58.Encode(ctx.blockInfo.PrevBlockHash)) } //export luaGetDbHandle @@ -870,7 +871,7 @@ func luaCryptoSha256(L *LState, arg unsafe.Pointer, argLen C.int) (*C.char, *C.c if checkHexString(string(data)) { dataStr := data[2:] var err error - data, err = enc.HexDecode(string(dataStr)) + data, err = hex.Decode(string(dataStr)) if err != nil { return nil, C.CString("[Contract.LuaCryptoSha256] hex decoding error: " + err.Error()) } @@ -879,14 +880,14 @@ func luaCryptoSha256(L *LState, arg unsafe.Pointer, argLen C.int) (*C.char, *C.c h.Write(data) resultHash := h.Sum(nil) - return C.CString("0x" + enc.HexEncode(resultHash)), nil + return C.CString("0x" + hex.Encode(resultHash)), nil } func decodeHex(hexStr string) ([]byte, error) { if checkHexString(hexStr) { hexStr = hexStr[2:] } - return enc.HexDecode(hexStr) + return hex.Decode(hexStr) } //export luaECVerify @@ -970,7 +971,7 @@ func luaCryptoToBytes(data unsafe.Pointer, dataLen C.int) ([]byte, bool) { isHex := checkHexString(string(b)) if isHex { var err error - d, err = enc.HexDecode(string(b[2:])) + d, err = hex.Decode(string(b[2:])) if err != nil { isHex = false } @@ -1022,7 +1023,7 @@ func luaCryptoKeccak256(data unsafe.Pointer, dataLen C.int) (unsafe.Pointer, int d, isHex := luaCryptoToBytes(data, dataLen) h := keccak256(d) if isHex { - hexb := []byte("0x" + enc.HexEncode(h)) + hexb := []byte("0x" + hex.Encode(h)) return C.CBytes(hexb), len(hexb) } else { return C.CBytes(h), len(h) diff --git a/contract/vm_direct/vm_direct.go b/contract/vm_direct/vm_direct.go index d66c24c5a..569a6f219 100644 --- a/contract/vm_direct/vm_direct.go +++ b/contract/vm_direct/vm_direct.go @@ -18,7 +18,7 @@ import ( "github.com/aergoio/aergo/v2/contract/name" "github.com/aergoio/aergo/v2/contract/system" "github.com/aergoio/aergo/v2/fee" - "github.com/aergoio/aergo/v2/internal/enc" + "github.com/aergoio/aergo/v2/internal/enc/base58" "github.com/aergoio/aergo/v2/state" "github.com/aergoio/aergo/v2/types" ) @@ -283,7 +283,7 @@ func NewTxExecutor(execCtx context.Context, ccc consensus.ChainConsensusCluster, err := executeTx(execCtx, ccc, cdb, blockState, tx, bi, preloadService) if err != nil { - logger.Error().Err(err).Str("hash", enc.B58Encode(tx.GetHash())).Msg("tx failed") + logger.Error().Err(err).Str("hash", base58.Encode(tx.GetHash())).Msg("tx failed") if err2 := blockState.Rollback(blockSnap); err2 != nil { logger.Panic().Err(err).Msg("failed to rollback block state") } @@ -460,7 +460,7 @@ func executeTx( sender.Balance().String(), tx.GetBody().GetAmountBigInt().String(), bs.GasPrice.String(), - bi.No, enc.B58Encode(tx.GetHash())) + bi.No, base58.Encode(tx.GetHash())) return err } @@ -494,7 +494,7 @@ func executeTx( txFee = new(big.Int).SetUint64(0) events, err = executeGovernanceTx(ccc, bs, txBody, sender, receiver, bi) if err != nil { - logger.Warn().Err(err).Str("txhash", enc.B58Encode(tx.GetHash())).Msg("governance tx Error") + logger.Warn().Err(err).Str("txhash", base58.Encode(tx.GetHash())).Msg("governance tx Error") } case types.TxType_FEEDELEGATION: balance := receiver.Balance() @@ -515,7 +515,7 @@ func executeTx( tx.GetHash(), txBody.GetAccount(), txBody.GetAmount()) if err != nil { if err != types.ErrNotAllowedFeeDelegation { - logger.Warn().Err(err).Str("txhash", enc.B58Encode(tx.GetHash())).Msg("checkFeeDelegation Error") + logger.Warn().Err(err).Str("txhash", base58.Encode(tx.GetHash())).Msg("checkFeeDelegation Error") return err } return types.ErrNotAllowedFeeDelegation diff --git a/contract/vm_dummy/vm_dummy.go b/contract/vm_dummy/vm_dummy.go index 82cfa8ae6..b76fac7f3 100644 --- a/contract/vm_dummy/vm_dummy.go +++ b/contract/vm_dummy/vm_dummy.go @@ -20,7 +20,7 @@ import ( "github.com/aergoio/aergo/v2/contract" "github.com/aergoio/aergo/v2/contract/system" "github.com/aergoio/aergo/v2/fee" - "github.com/aergoio/aergo/v2/internal/enc" + "github.com/aergoio/aergo/v2/internal/enc/base58" "github.com/aergoio/aergo/v2/state" "github.com/aergoio/aergo/v2/types" sha256 "github.com/minio/sha256-simd" @@ -477,7 +477,7 @@ func contractFrame(l luaTxContract, bs *state.BlockState, cdb contract.ChainAcce l.Hash(), l.sender(), l.amount().Bytes()) if err != nil { if err != types.ErrNotAllowedFeeDelegation { - logger.Debug().Err(err).Str("txhash", enc.B58Encode(l.Hash())).Msg("checkFeeDelegation Error") + logger.Debug().Err(err).Str("txhash", base58.Encode(l.Hash())).Msg("checkFeeDelegation Error") return err } return types.ErrNotAllowedFeeDelegation diff --git a/internal/enc/base58.go b/internal/enc/base58.go deleted file mode 100644 index bf28f3ce5..000000000 --- a/internal/enc/base58.go +++ /dev/null @@ -1,20 +0,0 @@ -package enc - -import ( - "github.com/mr-tron/base58/base58" -) - -// B58Encode returns human-readable (base58) string from b. Calling with empty or nil slice returns empty string. -func B58Encode(b []byte) string { - return base58.Encode(b) -} - -// B58Decode returns byte slice from human-readable (base58) string. Calling with empty string returns zero length string error. -func B58Decode(s string) ([]byte, error) { - return base58.Decode(s) -} - -func B58DecodeOrNil(s string) []byte { - buf, _ := B58Decode(s) - return buf -} diff --git a/internal/enc/base58/base58.go b/internal/enc/base58/base58.go new file mode 100644 index 000000000..118016562 --- /dev/null +++ b/internal/enc/base58/base58.go @@ -0,0 +1,20 @@ +package base58 + +import ( + "github.com/mr-tron/base58/base58" +) + +// Encode returns human-readable (base58) string from b. Calling with empty or nil slice returns empty string. +func Encode(b []byte) string { + return base58.Encode(b) +} + +// Decode returns byte slice from human-readable (base58) string. Calling with empty string returns zero length string error. +func Decode(s string) ([]byte, error) { + return base58.Decode(s) +} + +func DecodeOrNil(s string) []byte { + buf, _ := Decode(s) + return buf +} diff --git a/internal/enc/base58_test.go b/internal/enc/base58/base58_test.go similarity index 90% rename from internal/enc/base58_test.go rename to internal/enc/base58/base58_test.go index 4450469e4..dfe96e6af 100644 --- a/internal/enc/base58_test.go +++ b/internal/enc/base58/base58_test.go @@ -1,4 +1,4 @@ -package enc +package base58 import ( "bytes" @@ -22,13 +22,13 @@ func TestB58Encode(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - got := B58Encode(tt.args.b) + got := Encode(tt.args.b) if got != tt.want { t.Errorf("ToString() = %v, want %v", got, tt.want) } if tt.wantInverse { - got2, err := B58Decode(got) + got2, err := Decode(got) if err != nil { t.Errorf("ToBytes() = %s, want no err", err.Error()) } diff --git a/internal/enc/base58check.go b/internal/enc/base58check.go deleted file mode 100644 index 24bed42b4..000000000 --- a/internal/enc/base58check.go +++ /dev/null @@ -1,23 +0,0 @@ -package enc - -import ( - "github.com/anaskhan96/base58check" -) - -func B58CheckEncode(version string, data string) (string, error) { - return base58check.Encode(version, data) -} - -func B58CheckEncodeOrNil(version string, data string) string { - buf, _ := B58CheckEncode(version, data) - return buf -} - -func B58CheckDecode(encoded string) (string, error) { - return base58check.Decode(encoded) -} - -func B58CheckDecodeOrNil(encoded string) string { - buf, _ := B58CheckDecode(encoded) - return buf -} diff --git a/internal/enc/base58check/base58check.go b/internal/enc/base58check/base58check.go new file mode 100644 index 000000000..9233721c6 --- /dev/null +++ b/internal/enc/base58check/base58check.go @@ -0,0 +1,23 @@ +package base58check + +import ( + "github.com/anaskhan96/base58check" +) + +func Encode(version string, data string) (string, error) { + return base58check.Encode(version, data) +} + +func EncodeOrNil(version string, data string) string { + buf, _ := Encode(version, data) + return buf +} + +func Decode(encoded string) (string, error) { + return base58check.Decode(encoded) +} + +func DecodeOrNil(encoded string) string { + buf, _ := Decode(encoded) + return buf +} diff --git a/internal/enc/base58check_test.go b/internal/enc/base58check/base58check_test.go similarity index 56% rename from internal/enc/base58check_test.go rename to internal/enc/base58check/base58check_test.go index e00d762f8..dc8e9ac10 100644 --- a/internal/enc/base58check_test.go +++ b/internal/enc/base58check/base58check_test.go @@ -1,8 +1,9 @@ -package enc +package base58check import ( "testing" + "github.com/aergoio/aergo/v2/internal/enc/hex" "github.com/stretchr/testify/require" ) @@ -13,16 +14,16 @@ func TestB58CheckEncode(t *testing.T) { data string expect string }{ - {"T1", HexEncode([]byte{0}), HexEncode([]byte("Hello")), "1vSxRbq6DSYXc"}, - {"T2", HexEncode([]byte{1}), HexEncode([]byte("Hello")), "5BShidwAu2ieX"}, - {"T3", HexEncode([]byte{5}), HexEncode([]byte("abcdefghijklmnopqrstuvwxyz1234567890")), "2BSSzM1LQHgVeyiCPn5bEfgWY3HmiC3cbjGYFhTs1bVv5GTT7nJ8ajSE"}, + {"T1", hex.Encode([]byte{0}), hex.Encode([]byte("Hello")), "1vSxRbq6DSYXc"}, + {"T2", hex.Encode([]byte{1}), hex.Encode([]byte("Hello")), "5BShidwAu2ieX"}, + {"T3", hex.Encode([]byte{5}), hex.Encode([]byte("abcdefghijklmnopqrstuvwxyz1234567890")), "2BSSzM1LQHgVeyiCPn5bEfgWY3HmiC3cbjGYFhTs1bVv5GTT7nJ8ajSE"}, } { t.Run(test.name, func(t *testing.T) { - got, err := B58CheckEncode(test.version, test.data) + got, err := Encode(test.version, test.data) require.NoErrorf(t, err, "B58CheckEncode() error = %v", err) require.Equalf(t, test.expect, got, "B58CheckEncode() = %v, want %v", got, test.expect) - recover, err := B58CheckDecode(got) + recover, err := Decode(got) require.NoErrorf(t, err, "B58CheckDecode() error = %v", err) require.Equalf(t, test.version+test.data, recover, "B58CheckDecode() = %v, want %v", recover, test.version+test.data) }) diff --git a/internal/enc/base64.go b/internal/enc/base64/base64.go similarity index 57% rename from internal/enc/base64.go rename to internal/enc/base64/base64.go index da27e7bed..999484323 100644 --- a/internal/enc/base64.go +++ b/internal/enc/base64/base64.go @@ -1,17 +1,17 @@ -package enc +package base64 import "encoding/base64" -func B64Encode(s []byte) string { +func Encode(s []byte) string { return base64.StdEncoding.EncodeToString(s) } -func B64Decode(s string) ([]byte, error) { +func Decode(s string) ([]byte, error) { return base64.StdEncoding.DecodeString(s) } // Do not use processing real data, Only use for Logging or Testing. -func B64DecodeOrNil(s string) []byte { - buf, _ := B64Decode(s) +func DecodeOrNil(s string) []byte { + buf, _ := Decode(s) return buf } diff --git a/internal/enc/gob.go b/internal/enc/gob/gob.go similarity index 53% rename from internal/enc/gob.go rename to internal/enc/gob/gob.go index def0e8bf0..be2baa1c5 100644 --- a/internal/enc/gob.go +++ b/internal/enc/gob/gob.go @@ -1,12 +1,12 @@ -package enc +package gob import ( "bytes" "encoding/gob" ) -// GobEncode encodes e by using gob and returns. -func GobEncode(e interface{}) ([]byte, error) { +// Encode encodes e by using gob and returns. +func Encode(e interface{}) ([]byte, error) { var buf bytes.Buffer err := gob.NewEncoder(&buf).Encode(e) if err != nil { @@ -15,8 +15,8 @@ func GobEncode(e interface{}) ([]byte, error) { return buf.Bytes(), nil } -// GobDecode decodes a gob-encoded value v. -func GobDecode(v []byte, e interface{}) error { +// Decode decodes a gob-encoded value v. +func Decode(v []byte, e interface{}) error { dec := gob.NewDecoder(bytes.NewBuffer(v)) return dec.Decode(e) } diff --git a/internal/enc/gob_test.go b/internal/enc/gob/gob_test.go similarity index 79% rename from internal/enc/gob_test.go rename to internal/enc/gob/gob_test.go index cfa215281..b4300cabc 100644 --- a/internal/enc/gob_test.go +++ b/internal/enc/gob/gob_test.go @@ -1,4 +1,4 @@ -package enc +package gob import ( "testing" @@ -10,11 +10,11 @@ func TestGobCodec(t *testing.T) { a := assert.New(t) x := []int{1, 2, 3} - b, err := GobEncode(x) + b, err := Encode(x) a.Nil(err) y := []int{0, 0, 0} - err = GobDecode(b, &y) + err = Decode(b, &y) a.Nil(err) for i, v := range x { diff --git a/internal/enc/hex.go b/internal/enc/hex.go deleted file mode 100644 index 148a65a73..000000000 --- a/internal/enc/hex.go +++ /dev/null @@ -1,11 +0,0 @@ -package enc - -import "encoding/hex" - -func HexEncode(b []byte) string { - return hex.EncodeToString(b) -} - -func HexDecode(s string) ([]byte, error) { - return hex.DecodeString(s) -} diff --git a/internal/enc/hex/hex.go b/internal/enc/hex/hex.go new file mode 100644 index 000000000..6c484ee4d --- /dev/null +++ b/internal/enc/hex/hex.go @@ -0,0 +1,11 @@ +package hex + +import "encoding/hex" + +func Encode(b []byte) string { + return hex.EncodeToString(b) +} + +func Decode(s string) ([]byte, error) { + return hex.DecodeString(s) +} diff --git a/internal/merkle/merkle_test.go b/internal/merkle/merkle_test.go index edc09c497..7a8d0a68c 100644 --- a/internal/merkle/merkle_test.go +++ b/internal/merkle/merkle_test.go @@ -6,7 +6,7 @@ import ( "hash" "testing" - "github.com/aergoio/aergo/v2/internal/enc" + "github.com/aergoio/aergo/v2/internal/enc/base64" "github.com/minio/sha256-simd" "github.com/stretchr/testify/assert" ) @@ -91,7 +91,7 @@ func TestMerkle2Tx(t *testing.T) { for i, merkle := range merkles { assert.Equal(t, len(merkle), 32) - t.Logf("%d:%v", i, enc.B64Encode(merkle)) + t.Logf("%d:%v", i, base64.Encode(merkle)) } } @@ -114,7 +114,7 @@ func TestMerkle3Tx(t *testing.T) { for i, merkle := range merkles { assert.NotNil(t, merkle, "nil=%d", i) assert.Equal(t, len(merkle), 32) - t.Logf("%d:%v", i, enc.B64Encode(merkle)) + t.Logf("%d:%v", i, base64.Encode(merkle)) } } diff --git a/mempool/mempool.go b/mempool/mempool.go index 6a31f80ff..7c9ae89fa 100644 --- a/mempool/mempool.go +++ b/mempool/mempool.go @@ -28,7 +28,7 @@ import ( "github.com/aergoio/aergo/v2/contract/system" "github.com/aergoio/aergo/v2/fee" "github.com/aergoio/aergo/v2/internal/common" - "github.com/aergoio/aergo/v2/internal/enc" + "github.com/aergoio/aergo/v2/internal/enc/base58" "github.com/aergoio/aergo/v2/message" "github.com/aergoio/aergo/v2/pkg/component" "github.com/aergoio/aergo/v2/state" @@ -252,7 +252,7 @@ func (mp *MemPool) Receive(context actor.Context) { Err: errs, }) case *message.MemPoolDelTx: - mp.Info().Str("txhash", enc.B58Encode(msg.Tx.GetHash())).Msg("remove tx in mempool") + mp.Info().Str("txhash", base58.Encode(msg.Tx.GetHash())).Msg("remove tx in mempool") err := mp.removeTx(msg.Tx) context.Respond(&message.MemPoolDelTxRsp{ Err: err, @@ -451,8 +451,8 @@ func (mp *MemPool) setStateDB(block *types.Block) (bool, bool) { } mp.Debug().Str("Hash", newBlockID.String()). Str("StateRoot", types.ToHashID(stateRoot).String()). - Str("chainidhash", enc.B58Encode(mp.bestChainIdHash)). - Str("next chainidhash", enc.B58Encode(mp.acceptChainIdHash)). + Str("chainidhash", base58.Encode(mp.bestChainIdHash)). + Str("next chainidhash", base58.Encode(mp.acceptChainIdHash)). Msg("new StateDB opened") } else if !bytes.Equal(mp.stateDB.GetRoot(), stateRoot) { if err := mp.stateDB.SetRoot(stateRoot); err != nil { @@ -801,7 +801,7 @@ func (mp *MemPool) getAccountState(acc []byte) (*types.State, error) { state, err := mp.stateDB.GetAccountState(types.ToAccountID(acc)) if err != nil { - mp.Fatal().Err(err).Str("sroot", enc.B58Encode(mp.stateDB.GetRoot())).Msg("failed to get state") + mp.Fatal().Err(err).Str("sroot", base58.Encode(mp.stateDB.GetRoot())).Msg("failed to get state") //FIXME PANIC? //mp.Fatal().Err(err).Msg("failed to get state") @@ -959,7 +959,7 @@ func (mp *MemPool) removeTx(tx *types.Tx) error { defer mp.Unlock() if mp.exist(tx.GetHash()) == nil { - mp.Warn().Str("txhash", enc.B58Encode(tx.GetHash())).Msg("could not find tx to remove") + mp.Warn().Str("txhash", base58.Encode(tx.GetHash())).Msg("could not find tx to remove") return types.ErrTxNotFound } acc := tx.GetBody().GetAccount() @@ -969,7 +969,7 @@ func (mp *MemPool) removeTx(tx *types.Tx) error { } newOrphan, removed := list.RemoveTx(tx) if removed == nil { - mp.Error().Str("txhash", enc.B58Encode(tx.GetHash())).Msg("already removed tx") + mp.Error().Str("txhash", base58.Encode(tx.GetHash())).Msg("already removed tx") } mp.orphan += newOrphan mp.releaseMemPoolList(list) diff --git a/mempool/txverifier.go b/mempool/txverifier.go index 28f311944..4380692ad 100644 --- a/mempool/txverifier.go +++ b/mempool/txverifier.go @@ -2,7 +2,7 @@ package mempool import ( "github.com/aergoio/aergo-actor/actor" - "github.com/aergoio/aergo/v2/internal/enc" + "github.com/aergoio/aergo/v2/internal/enc/base58" "github.com/aergoio/aergo/v2/message" "github.com/aergoio/aergo/v2/types" ) @@ -31,7 +31,7 @@ func (s *TxVerifier) Receive(context actor.Context) { err = s.mp.put(tx) } if err != nil { - s.mp.Logger.Info().Err(err).Str("txID", enc.B58Encode(msg.GetHash())).Msg("tx verification failed") + s.mp.Logger.Info().Err(err).Str("txID", base58.Encode(msg.GetHash())).Msg("tx verification failed") } } context.Respond(&message.MemPoolPutRsp{Err: err}) diff --git a/p2p/actorwork.go b/p2p/actorwork.go index 1c301ed83..d7075b696 100644 --- a/p2p/actorwork.go +++ b/p2p/actorwork.go @@ -11,7 +11,7 @@ import ( "time" "github.com/aergoio/aergo-actor/actor" - "github.com/aergoio/aergo/v2/internal/enc" + "github.com/aergoio/aergo/v2/internal/enc/base58" "github.com/aergoio/aergo/v2/message" "github.com/aergoio/aergo/v2/p2p/p2pcommon" "github.com/aergoio/aergo/v2/p2p/p2putil" @@ -141,7 +141,7 @@ func (p2ps *P2P) NotifyNewBlock(blockNotice message.NotifyNewBlock) bool { } } - p2ps.Debug().Int("skipped_cnt", skipped).Int("sent_cnt", sent).Str("hash", enc.B58Encode(blockNotice.Block.BlockHash())).Msg("Notifying new block") + p2ps.Debug().Int("skipped_cnt", skipped).Int("sent_cnt", sent).Str("hash", base58.Encode(blockNotice.Block.BlockHash())).Msg("Notifying new block") return true } @@ -162,7 +162,7 @@ func (p2ps *P2P) NotifyBlockProduced(blockNotice message.NotifyNewBlock) bool { } } - p2ps.Debug().Int("skipped_cnt", skipped).Int("sent_cnt", sent).Str("hash", enc.B58Encode(blockNotice.Block.BlockHash())).Uint64("block_no", req.BlockNo).Msg("Notifying block produced") + p2ps.Debug().Int("skipped_cnt", skipped).Int("sent_cnt", sent).Str("hash", base58.Encode(blockNotice.Block.BlockHash())).Uint64("block_no", req.BlockNo).Msg("Notifying block produced") return true } diff --git a/p2p/const_test.go b/p2p/const_test.go index a0e6b7fb3..0d53fdbcf 100644 --- a/p2p/const_test.go +++ b/p2p/const_test.go @@ -11,7 +11,9 @@ import ( "testing" "github.com/aergoio/aergo-lib/log" - "github.com/aergoio/aergo/v2/internal/enc" + "github.com/aergoio/aergo/v2/internal/enc/base58" + "github.com/aergoio/aergo/v2/internal/enc/base64" + "github.com/aergoio/aergo/v2/internal/enc/hex" "github.com/aergoio/aergo/v2/p2p/p2pcommon" "github.com/aergoio/aergo/v2/p2p/p2pmock" "github.com/aergoio/aergo/v2/types" @@ -21,9 +23,9 @@ import ( // this file collect sample global constants used in unit test. I'm tired of creating less meaningful variables in each tests. -var dummyBlockHash, _ = enc.HexDecode("4f461d85e869ade8a0544f8313987c33a9c06534e50c4ad941498299579bd7ac") +var dummyBlockHash, _ = hex.Decode("4f461d85e869ade8a0544f8313987c33a9c06534e50c4ad941498299579bd7ac") var dummyBlockHeight uint64 = 100215 -var dummyTxHash, _ = enc.B58Decode("4H4zAkAyRV253K5SNBJtBxqUgHEbZcXbWFFc6cmQHY45") +var dummyTxHash, _ = base58.Decode("4H4zAkAyRV253K5SNBJtBxqUgHEbZcXbWFFc6cmQHY45") var samplePeerID types.PeerID var sampleMeta p2pcommon.PeerMeta @@ -65,9 +67,9 @@ var dummyBestBlock *types.Block var dummyMeta p2pcommon.PeerMeta func init() { - bytes, _ := enc.B64Decode(sampleKey1PrivBase64) + bytes, _ := base64.Decode(sampleKey1PrivBase64) sampleKey1Priv, _ = crypto.UnmarshalPrivateKey(bytes) - bytes, _ = enc.B64Decode(sampelKey1PubBase64) + bytes, _ = base64.Decode(sampelKey1PubBase64) sampleKey1Pub, _ = crypto.UnmarshalPublicKey(bytes) if !sampleKey1Priv.GetPublic().Equals(sampleKey1Pub) { panic("problem in pk generation ") @@ -77,7 +79,7 @@ func init() { panic("problem in id generation") } - bytes, _ = enc.B64Decode(sampleKey2PrivBase64) + bytes, _ = base64.Decode(sampleKey2PrivBase64) sampleKey2Priv, _ = crypto.UnmarshalPrivateKey(bytes) sampleKey2Pub = sampleKey2Priv.GetPublic() sampleKey2ID, _ = types.IDFromPublicKey(sampleKey2Pub) @@ -119,7 +121,7 @@ func init() { sampleTxs = make([][]byte, len(sampleTxsB58)) sampleTxIDs = make([]types.TxID, len(sampleTxsB58)) for i, hashb58 := range sampleTxsB58 { - hash, _ := enc.B58Decode(hashb58) + hash, _ := base58.Decode(hashb58) sampleTxs[i] = hash copy(sampleTxIDs[i][:], hash) } @@ -127,7 +129,7 @@ func init() { sampleBlks = make([][]byte, len(sampleBlksB58)) sampleBlksIDs = make([]types.BlockID, len(sampleBlksB58)) for i, hashb58 := range sampleTxsB58 { - hash, _ := enc.B58Decode(hashb58) + hash, _ := base58.Decode(hashb58) sampleBlks[i] = hash copy(sampleBlksIDs[i][:], hash) } @@ -147,7 +149,7 @@ func createDummyMo(ctrl *gomock.Controller) *p2pmock.MockMsgOrder { func TestTXIDs(t *testing.T) { for i := 0; i < len(sampleTxIDs); i++ { if !bytes.Equal(sampleTxs[i], sampleTxIDs[i][:]) { - t.Errorf("TX hash %v and converted ID %v are differ.", enc.B58Encode(sampleTxs[i]), sampleTxIDs[i]) + t.Errorf("TX hash %v and converted ID %v are differ.", base58.Encode(sampleTxs[i]), sampleTxIDs[i]) } } } @@ -155,7 +157,7 @@ func TestTXIDs(t *testing.T) { func TestBlockIDs(t *testing.T) { for i := 0; i < len(sampleBlksIDs); i++ { if !bytes.Equal(sampleBlks[i], sampleBlksIDs[i][:]) { - t.Errorf("TX hash %v and converted ID %v are differ.", enc.B58Encode(sampleBlks[i]), sampleBlksIDs[i]) + t.Errorf("TX hash %v and converted ID %v are differ.", base58.Encode(sampleBlks[i]), sampleBlksIDs[i]) } } } @@ -265,12 +267,12 @@ var testIn = []string{ func TestMoreTXIDs(t *testing.T) { for _, in := range testIn { - hash, _ := enc.B58Decode(in) + hash, _ := base58.Decode(in) id, err := types.ParseToTxID(hash) if err != nil { - t.Errorf("Failed to parse TX hash %v : %v", enc.B58Encode(hash), err) + t.Errorf("Failed to parse TX hash %v : %v", base58.Encode(hash), err) } else if !bytes.Equal(hash, id[:]) { - t.Errorf("TX hash %v and converted ID %v are differ.", enc.B58Encode(hash), id) + t.Errorf("TX hash %v and converted ID %v are differ.", base58.Encode(hash), id) } } } diff --git a/p2p/hashreceiver_test.go b/p2p/hashreceiver_test.go index c8f57e297..bd69d0a84 100644 --- a/p2p/hashreceiver_test.go +++ b/p2p/hashreceiver_test.go @@ -10,7 +10,7 @@ import ( "time" "github.com/aergoio/aergo/v2/chain" - "github.com/aergoio/aergo/v2/internal/enc" + "github.com/aergoio/aergo/v2/internal/enc/base58" "github.com/aergoio/aergo/v2/message" "github.com/aergoio/aergo/v2/p2p/p2pcommon" "github.com/aergoio/aergo/v2/p2p/p2pmock" @@ -120,7 +120,7 @@ func TestBlockHashesReceiver_ReceiveResp(t *testing.T) { for _, h := range arg.Hashes { _, err := types.ParseToBlockID(h) if err != nil { - t.Fatalf("Wrong block hash %s, err %v)", enc.B58Encode(h), err.Error()) + t.Fatalf("Wrong block hash %s, err %v)", base58.Encode(h), err.Error()) } } } diff --git a/p2p/msgorder.go b/p2p/msgorder.go index bd1747db6..6c3f255be 100644 --- a/p2p/msgorder.go +++ b/p2p/msgorder.go @@ -9,7 +9,7 @@ import ( "time" "github.com/aergoio/aergo/v2/consensus" - "github.com/aergoio/aergo/v2/internal/enc" + "github.com/aergoio/aergo/v2/internal/enc/base58" "github.com/aergoio/aergo/v2/p2p/p2pcommon" "github.com/aergoio/aergo/v2/p2p/p2putil" "github.com/aergoio/aergo/v2/p2p/raftsupport" @@ -169,7 +169,7 @@ func (pr *pbBpNoticeOrder) SendTo(pi p2pcommon.RemotePeer) error { } if pr.trace { p.logger.Debug().Str(p2putil.LogPeerName, p.Name()).Stringer(p2putil.LogProtoID, pr.GetProtocolID()). - Str(p2putil.LogMsgID, pr.GetMsgID().String()).Str(p2putil.LogBlkHash, enc.B58Encode(pr.block.Hash)).Msg("Notify block produced") + Str(p2putil.LogMsgID, pr.GetMsgID().String()).Str(p2putil.LogBlkHash, base58.Encode(pr.block.Hash)).Msg("Notify block produced") } return nil } diff --git a/p2p/p2pkey/nodekey.go b/p2p/p2pkey/nodekey.go index 9e5d6d013..9190c0faa 100644 --- a/p2p/p2pkey/nodekey.go +++ b/p2p/p2pkey/nodekey.go @@ -12,7 +12,7 @@ import ( "github.com/aergoio/aergo-lib/log" "github.com/aergoio/aergo/v2/config" - "github.com/aergoio/aergo/v2/internal/enc" + "github.com/aergoio/aergo/v2/internal/enc/base58" "github.com/aergoio/aergo/v2/p2p/p2pcommon" "github.com/aergoio/aergo/v2/p2p/p2putil" "github.com/aergoio/aergo/v2/types" @@ -72,7 +72,7 @@ func InitNodeInfo(baseCfg *config.BaseConfig, p2pCfg *config.P2PConfig, version ni = &nodeInfo{ id: id, - sid: enc.B58Encode([]byte(id)), + sid: base58.Encode([]byte(id)), pubKey: pub, privKey: priv, version: version, diff --git a/p2p/p2putil/PKTest_test.go b/p2p/p2putil/PKTest_test.go index 40946a69b..6cb233c70 100644 --- a/p2p/p2putil/PKTest_test.go +++ b/p2p/p2putil/PKTest_test.go @@ -3,7 +3,7 @@ package p2putil import ( "testing" - "github.com/aergoio/aergo/v2/internal/enc" + "github.com/aergoio/aergo/v2/internal/enc/hex" "github.com/btcsuite/btcd/btcec" "github.com/libp2p/go-libp2p-core/crypto" ) @@ -26,15 +26,15 @@ func PrintLibP2PKey(priv crypto.Key, marshaled []byte, t *testing.T) { if err != nil { t.Errorf("Failed to get bytes: %v", err.Error()) } else { - t.Logf("BT/MAR %v", enc.HexEncode(oldBytes)) - t.Logf("RAW %v", enc.HexEncode(newBytes)) + t.Logf("BT/MAR %v", hex.Encode(oldBytes)) + t.Logf("RAW %v", hex.Encode(newBytes)) } } func PrintBTCPKey(priv *btcec.PrivateKey, t *testing.T) { oldBytes := priv.Serialize() - t.Logf("PRIV %v", enc.HexEncode(oldBytes)) - t.Logf("PUBLIC %v", enc.HexEncode(priv.PubKey().SerializeCompressed())) + t.Logf("PRIV %v", hex.Encode(oldBytes)) + t.Logf("PUBLIC %v", hex.Encode(priv.PubKey().SerializeCompressed())) } func TestLibs(t *testing.T) { diff --git a/p2p/p2putil/certificate_test.go b/p2p/p2putil/certificate_test.go index 135225e3b..a41d726c2 100644 --- a/p2p/p2putil/certificate_test.go +++ b/p2p/p2putil/certificate_test.go @@ -6,7 +6,7 @@ import ( "testing" "time" - "github.com/aergoio/aergo/v2/internal/enc" + "github.com/aergoio/aergo/v2/internal/enc/base58" "github.com/aergoio/aergo/v2/p2p/p2pcommon" "github.com/aergoio/aergo/v2/types" "github.com/btcsuite/btcd/btcec" @@ -51,7 +51,7 @@ func TestNewAgentCertV1(t *testing.T) { t.Errorf("NewAgentCertV1() bpID = %v, want %v", got.AgentID, tt.args.agentID) } if !got.BPPubKey.IsEqual(tt.args.bpKey.PubKey()) { - t.Errorf("NewAgentCertV1() pubKey = %v, want %v", enc.B58Encode(got.BPPubKey.SerializeCompressed()), enc.B58Encode(tt.args.bpKey.PubKey().SerializeCompressed())) + t.Errorf("NewAgentCertV1() pubKey = %v, want %v", base58.Encode(got.BPPubKey.SerializeCompressed()), base58.Encode(tt.args.bpKey.PubKey().SerializeCompressed())) } if !types.IsSamePeerID(got.BPID, tt.args.bpID) { t.Errorf("NewAgentCertV1() bpID = %v, want %v", got.BPID, tt.args.bpID) @@ -258,7 +258,7 @@ func Test_calculateCertificateHash(t *testing.T) { } if !bytes.Equal(h1, h11) { - t.Fatalf("calculated hash is differ! %v , want %v ", enc.B58Encode(h11), enc.B58Encode(h1)) + t.Fatalf("calculated hash is differ! %v , want %v ", base58.Encode(h11), base58.Encode(h1)) } h2, err := calculateCertificateHash(w2) if err != nil { @@ -266,7 +266,7 @@ func Test_calculateCertificateHash(t *testing.T) { } if bytes.Equal(h1, h2) { - t.Fatalf("calculated hash is same! %v , want different ", enc.B58Encode(h2)) + t.Fatalf("calculated hash is same! %v , want different ", base58.Encode(h2)) } } diff --git a/p2p/p2putil/cryptoutil_test.go b/p2p/p2putil/cryptoutil_test.go index 7670620ca..07e192f99 100644 --- a/p2p/p2putil/cryptoutil_test.go +++ b/p2p/p2putil/cryptoutil_test.go @@ -4,7 +4,7 @@ import ( "bytes" "testing" - "github.com/aergoio/aergo/v2/internal/enc" + "github.com/aergoio/aergo/v2/internal/enc/hex" "github.com/btcsuite/btcd/btcec" "github.com/libp2p/go-libp2p-core/crypto" ) @@ -27,11 +27,11 @@ func TestConvertPKToLibP2P(t *testing.T) { } raw, err := got.Raw() if !bytes.Equal(raw, btcPK.Serialize()) { - t.Errorf("ConvertPKToLibP2P() pk = %v, want %v", enc.HexEncode(raw), enc.HexEncode(btcPK.Serialize())) + t.Errorf("ConvertPKToLibP2P() pk = %v, want %v", hex.Encode(raw), hex.Encode(btcPK.Serialize())) } rev := ConvertPKToBTCEC(got) if !bytes.Equal(rev.Serialize(), btcPK.Serialize()) { - t.Errorf("ConvertPKToBTCEC() pk = %v, want %v", enc.HexEncode(rev.Serialize()), enc.HexEncode(btcPK.Serialize())) + t.Errorf("ConvertPKToBTCEC() pk = %v, want %v", hex.Encode(rev.Serialize()), hex.Encode(btcPK.Serialize())) } marshaled, err := crypto.MarshalPrivateKey(got) @@ -68,11 +68,11 @@ func TestConvertPubKeyToLibP2P(t *testing.T) { } raw, err := got.Raw() if !bytes.Equal(raw, pubKey.SerializeCompressed()) { - t.Errorf("ConvertPubToLibP2P() pk = %v, want %v", enc.HexEncode(raw), enc.HexEncode(pubKey.SerializeCompressed())) + t.Errorf("ConvertPubToLibP2P() pk = %v, want %v", hex.Encode(raw), hex.Encode(pubKey.SerializeCompressed())) } rev := ConvertPubKeyToBTCEC(got) if !bytes.Equal(rev.SerializeCompressed(), pubKey.SerializeCompressed()) { - t.Errorf("ConvertPubKeyToBTCEC() pk = %v, want %v", enc.HexEncode(rev.SerializeCompressed()), enc.HexEncode(pubKey.SerializeCompressed())) + t.Errorf("ConvertPubKeyToBTCEC() pk = %v, want %v", hex.Encode(rev.SerializeCompressed()), hex.Encode(pubKey.SerializeCompressed())) } }) } diff --git a/p2p/p2putil/protobuf_test.go b/p2p/p2putil/protobuf_test.go index 963d2b116..be7837396 100644 --- a/p2p/p2putil/protobuf_test.go +++ b/p2p/p2putil/protobuf_test.go @@ -9,22 +9,22 @@ import ( "fmt" "testing" - "github.com/aergoio/aergo/v2/internal/enc" + "github.com/aergoio/aergo/v2/internal/enc/base58" "github.com/aergoio/aergo/v2/types" "github.com/golang/protobuf/proto" "github.com/stretchr/testify/assert" ) -var dummyTxHash, _ = enc.B58Decode("4H4zAkAyRV253K5SNBJtBxqUgHEbZcXbWFFc6cmQHY45") +var dummyTxHash, _ = base58.Decode("4H4zAkAyRV253K5SNBJtBxqUgHEbZcXbWFFc6cmQHY45") func Test_MarshalTxResp(t *testing.T) { dummyTx := &types.Tx{Hash: dummyTxHash, Body: &types.TxBody{Payload: []byte("It's a good day to die.")}} txMarshaled, _ := proto.Marshal(dummyTx) txSize := len(dummyTxHash) + 2 + len(txMarshaled) + 2 // hash+ field desc of hash + tx+field desc of tx - //fmt.Println("TX : ",enc.HexEncode(txMarshaled)) + //fmt.Println("TX : ",hex.HexEncode(txMarshaled)) emptyMarshaled, _ := proto.Marshal(&types.GetTransactionsResponse{}) emptySize := len(emptyMarshaled) - //fmt.Println("EMPTY: ",enc.HexEncode(emptyMarshaled)) + //fmt.Println("EMPTY: ",hex.HexEncode(emptyMarshaled)) //fmt.Printf("Size of All nil: %d , tx size: %d ",emptySize, txSize) tests := []struct { name string @@ -59,7 +59,7 @@ func Test_MarshalTxResp(t *testing.T) { if actualSize < cut { cut = actualSize } - //fmt.Println("ACTUAL: ",enc.HexEncode(actual[:cut])) + //fmt.Println("ACTUAL: ",hex.HexEncode(actual[:cut])) assert.Equal(t, test.expectedSize, actualSize) diff --git a/p2p/p2putil/util.go b/p2p/p2putil/util.go index ab653222a..8eed9bf9a 100644 --- a/p2p/p2putil/util.go +++ b/p2p/p2putil/util.go @@ -13,7 +13,7 @@ import ( "strconv" "strings" - "github.com/aergoio/aergo/v2/internal/enc" + "github.com/aergoio/aergo/v2/internal/enc/base58" "github.com/aergoio/aergo/v2/message" "github.com/aergoio/aergo/v2/types" "github.com/gofrs/uuid" @@ -186,9 +186,9 @@ func PrintHashList(blocks []*types.Block) string { case 0: return "blk_cnt=0" case 1: - return fmt.Sprintf("blk_cnt=1,hash=%s(num %d)", enc.B58Encode(blocks[0].Hash), blocks[0].Header.BlockNo) + return fmt.Sprintf("blk_cnt=1,hash=%s(num %d)", base58.Encode(blocks[0].Hash), blocks[0].Header.BlockNo) default: - return fmt.Sprintf("blk_cnt=%d,firstHash=%s(num %d),lastHash=%s(num %d)", l, enc.B58Encode(blocks[0].Hash), blocks[0].Header.BlockNo, enc.B58Encode(blocks[l-1].Hash), blocks[l-1].Header.BlockNo) + return fmt.Sprintf("blk_cnt=%d,firstHash=%s(num %d),lastHash=%s(num %d)", l, base58.Encode(blocks[0].Hash), blocks[0].Header.BlockNo, base58.Encode(blocks[l-1].Hash), blocks[l-1].Header.BlockNo) } } diff --git a/p2p/p2putil/util_test.go b/p2p/p2putil/util_test.go index 5f7700578..e52b46fce 100644 --- a/p2p/p2putil/util_test.go +++ b/p2p/p2putil/util_test.go @@ -16,7 +16,7 @@ import ( "testing" "time" - "github.com/aergoio/aergo/v2/internal/enc" + "github.com/aergoio/aergo/v2/internal/enc/base58" "github.com/aergoio/aergo/v2/types" "github.com/gofrs/uuid" lru "github.com/hashicorp/golang-lru" @@ -111,10 +111,10 @@ func Test_Encode(t *testing.T) { } for _, test := range tests { t.Run(test.name, func(t *testing.T) { - got := enc.B58Encode(test.in) + got := base58.Encode(test.in) assert.Equal(t, test.out, got) if len(test.out) > 0 { - gotBytes, err := enc.B58Decode(test.out) + gotBytes, err := base58.Decode(test.out) assert.Nil(t, err) assert.Equal(t, test.in, gotBytes) } diff --git a/p2p/subproto/block.go b/p2p/subproto/block.go index 053d65514..00da901f6 100644 --- a/p2p/subproto/block.go +++ b/p2p/subproto/block.go @@ -7,7 +7,7 @@ package subproto import ( "github.com/aergoio/aergo-lib/log" - "github.com/aergoio/aergo/v2/internal/enc" + "github.com/aergoio/aergo/v2/internal/enc/base58" "github.com/aergoio/aergo/v2/message" "github.com/aergoio/aergo/v2/p2p/p2pcommon" "github.com/aergoio/aergo/v2/p2p/p2putil" @@ -162,7 +162,7 @@ func (bh *newBlockNoticeHandler) Handle(msg p2pcommon.Message, msgBody p2pcommon if blockID, err := types.ParseToBlockID(data.BlockHash); err != nil { // TODO Add penalty score and break - bh.logger.Info().Str(p2putil.LogPeerName, remotePeer.Name()).Str("hash", enc.B58Encode(data.BlockHash)).Msg("malformed blockHash") + bh.logger.Info().Str(p2putil.LogPeerName, remotePeer.Name()).Str("hash", base58.Encode(data.BlockHash)).Msg("malformed blockHash") return } else { // lru cache can't accept byte slice key @@ -242,7 +242,7 @@ func (bh *getAncestorRequestHandler) handleGetAncestorReq(msg p2pcommon.Message, AncestorNo: ancestor.No, } - bh.logger.Debug().Uint64("ancestorno", ancestor.No).Str("ancestorhash", enc.B58Encode(ancestor.Hash)).Msg("Sending get ancestor response") + bh.logger.Debug().Uint64("ancestorno", ancestor.No).Str("ancestorhash", base58.Encode(ancestor.Hash)).Msg("Sending get ancestor response") remotePeer.SendMessage(remotePeer.MF().NewMsgResponseOrder(msg.ID(), p2pcommon.GetAncestorResponse, resp)) } diff --git a/p2p/subproto/blockhash_test.go b/p2p/subproto/blockhash_test.go index a73fabe50..551290b69 100644 --- a/p2p/subproto/blockhash_test.go +++ b/p2p/subproto/blockhash_test.go @@ -13,7 +13,7 @@ import ( "github.com/aergoio/aergo-lib/log" "github.com/aergoio/aergo/v2/chain" - "github.com/aergoio/aergo/v2/internal/enc" + "github.com/aergoio/aergo/v2/internal/enc/base58" "github.com/aergoio/aergo/v2/p2p/p2pcommon" "github.com/aergoio/aergo/v2/p2p/p2pmock" "github.com/aergoio/aergo/v2/types" @@ -46,7 +46,7 @@ func TestGetHashRequestHandler_handle(t *testing.T) { sampleBlks = make([][]byte, len(sampleBlksB58)) sampleBlksHashes = make([]types.BlockID, len(sampleBlksB58)) for i, hashb58 := range sampleBlksB58 { - hash, _ := enc.B58Decode(hashb58) + hash, _ := base58.Decode(hashb58) sampleBlks[i] = hash copy(sampleBlksHashes[i][:], hash) } @@ -154,7 +154,7 @@ func TestGetHashByNoRequestHandler_handle(t *testing.T) { sampleBlks = make([][]byte, len(sampleBlksB58)) sampleBlksHashes = make([]types.BlockID, len(sampleBlksB58)) for i, hashb58 := range sampleBlksB58 { - hash, _ := enc.B58Decode(hashb58) + hash, _ := base58.Decode(hashb58) sampleBlks[i] = hash copy(sampleBlksHashes[i][:], hash) } diff --git a/p2p/subproto/bp.go b/p2p/subproto/bp.go index e92e448e7..3937949e9 100644 --- a/p2p/subproto/bp.go +++ b/p2p/subproto/bp.go @@ -7,7 +7,7 @@ package subproto import ( "github.com/aergoio/aergo-lib/log" - "github.com/aergoio/aergo/v2/internal/enc" + "github.com/aergoio/aergo/v2/internal/enc/base58" "github.com/aergoio/aergo/v2/message" "github.com/aergoio/aergo/v2/p2p/p2pcommon" "github.com/aergoio/aergo/v2/p2p/p2putil" @@ -48,7 +48,7 @@ func (h *blockProducedNoticeHandler) Handle(msg p2pcommon.Message, msgBody p2pco block := data.Block if blockID, err := types.ParseToBlockID(data.GetBlock().GetHash()); err != nil { // TODO add penalty score - h.logger.Info().Str(p2putil.LogPeerName, remotePeer.Name()).Str("hash", enc.B58Encode(data.GetBlock().GetHash())).Msg("malformed blockHash") + h.logger.Info().Str(p2putil.LogPeerName, remotePeer.Name()).Str("hash", base58.Encode(data.GetBlock().GetHash())).Msg("malformed blockHash") return } else { bpID, err := block.BPID() @@ -107,7 +107,7 @@ func (h *toAgentBPNoticeHandler) Handle(msg p2pcommon.Message, msgBody p2pcommon block := data.Block if blockID, err := types.ParseToBlockID(data.GetBlock().GetHash()); err != nil { // TODO add penalty score - h.logger.Info().Str(p2putil.LogPeerName, remotePeer.Name()).Str("hash", enc.B58Encode(data.GetBlock().GetHash())).Msg("malformed blockHash") + h.logger.Info().Str(p2putil.LogPeerName, remotePeer.Name()).Str("hash", base58.Encode(data.GetBlock().GetHash())).Msg("malformed blockHash") return } else { bpID, err := block.BPID() diff --git a/p2p/subproto/bp_test.go b/p2p/subproto/bp_test.go index 6a35f2ba7..eb823eaab 100644 --- a/p2p/subproto/bp_test.go +++ b/p2p/subproto/bp_test.go @@ -10,7 +10,7 @@ import ( "time" "github.com/aergoio/aergo-lib/log" - "github.com/aergoio/aergo/v2/internal/enc" + "github.com/aergoio/aergo/v2/internal/enc/base58" "github.com/aergoio/aergo/v2/p2p/p2pcommon" "github.com/aergoio/aergo/v2/p2p/p2pmock" "github.com/aergoio/aergo/v2/p2p/p2putil" @@ -65,7 +65,7 @@ func TestNewBlockProducedNoticeHandlerOfBP(t *testing.T) { func Test_blockProducedNoticeHandler_handle_FromBP(t *testing.T) { logger := log.NewLogger("test.subproto") - dummyBlockHash, _ := enc.B58Decode("v6zbuQ4aVSdbTwQhaiZGp5pcL5uL55X3kt2wfxor5W6") + dummyBlockHash, _ := base58.Decode("v6zbuQ4aVSdbTwQhaiZGp5pcL5uL55X3kt2wfxor5W6") dummyBlockID := types.MustParseBlockID(dummyBlockHash) bpKey, bpPub, _ := crypto.GenerateKeyPair(crypto.Secp256k1, 256) bpID, _ := types.IDFromPrivateKey(bpKey) diff --git a/p2p/subproto/getblock.go b/p2p/subproto/getblock.go index 9e501ff53..a58742a1a 100644 --- a/p2p/subproto/getblock.go +++ b/p2p/subproto/getblock.go @@ -9,7 +9,7 @@ import ( "time" "github.com/aergoio/aergo-lib/log" - "github.com/aergoio/aergo/v2/internal/enc" + "github.com/aergoio/aergo/v2/internal/enc/base58" "github.com/aergoio/aergo/v2/p2p/p2pcommon" "github.com/aergoio/aergo/v2/p2p/p2putil" "github.com/aergoio/aergo/v2/types" @@ -82,13 +82,13 @@ func (bh *blockRequestHandler) handleBlkReq(msg p2pcommon.Message, data *types.G foundBlock, err := bh.actor.GetChainAccessor().GetBlock(hash) if err != nil { // the block hash from request must exists. this error is fatal. - bh.logger.Warn().Err(err).Str(p2putil.LogBlkHash, enc.B58Encode(hash)).Str(p2putil.LogOrgReqID, requestID.String()).Msg("failed to get block while processing getBlock") + bh.logger.Warn().Err(err).Str(p2putil.LogBlkHash, base58.Encode(hash)).Str(p2putil.LogOrgReqID, requestID.String()).Msg("failed to get block while processing getBlock") status = types.ResultStatus_INTERNAL break } if foundBlock == nil { // the remote peer request not existing block - bh.logger.Debug().Str(p2putil.LogBlkHash, enc.B58Encode(hash)).Str(p2putil.LogOrgReqID, requestID.String()).Msg("requested block hash is missing") + bh.logger.Debug().Str(p2putil.LogBlkHash, base58.Encode(hash)).Str(p2putil.LogOrgReqID, requestID.String()).Msg("requested block hash is missing") status = types.ResultStatus_NOT_FOUND break diff --git a/p2p/subproto/getblock_test.go b/p2p/subproto/getblock_test.go index 08c557cdf..c4e2a13df 100644 --- a/p2p/subproto/getblock_test.go +++ b/p2p/subproto/getblock_test.go @@ -10,7 +10,7 @@ import ( "time" "github.com/aergoio/aergo-lib/log" - "github.com/aergoio/aergo/v2/internal/enc" + "github.com/aergoio/aergo/v2/internal/enc/base58" "github.com/aergoio/aergo/v2/message" "github.com/aergoio/aergo/v2/p2p/p2pcommon" "github.com/aergoio/aergo/v2/p2p/p2pmock" @@ -95,7 +95,7 @@ func TestBlockResponseHandler_handle(t *testing.T) { logger := log.NewLogger("test.subproto") var dummyPeerID, _ = types.IDB58Decode("16Uiu2HAmN5YU8V2LnTy9neuuJCLNsxLnd5xVSRZqkjvZUHS3mLoD") - dummyBlockHash, _ := enc.B58Decode("v6zbuQ4aVSdbTwQhaiZGp5pcL5uL55X3kt2wfxor5W6") + dummyBlockHash, _ := base58.Decode("v6zbuQ4aVSdbTwQhaiZGp5pcL5uL55X3kt2wfxor5W6") var sampleBlksB58 = []string{ "v6zbuQ4aVSdbTwQhaiZGp5pcL5uL55X3kt2wfxor5W6", "2VEPg4MqJUoaS3EhZ6WWSAUuFSuD4oSJ645kSQsGV7H9", @@ -110,7 +110,7 @@ func TestBlockResponseHandler_handle(t *testing.T) { sampleBlks = make([][]byte, len(sampleBlksB58)) sampleBlksHashes = make([]types.BlockID, len(sampleBlksB58)) for i, hashb58 := range sampleBlksB58 { - hash, _ := enc.B58Decode(hashb58) + hash, _ := base58.Decode(hashb58) sampleBlks[i] = hash copy(sampleBlksHashes[i][:], hash) } diff --git a/p2p/subproto/ping_test.go b/p2p/subproto/ping_test.go index 98563483f..6c0efeff8 100644 --- a/p2p/subproto/ping_test.go +++ b/p2p/subproto/ping_test.go @@ -3,7 +3,7 @@ package subproto import ( "testing" - "github.com/aergoio/aergo/v2/internal/enc" + "github.com/aergoio/aergo/v2/internal/enc/base58" "github.com/aergoio/aergo/v2/types" "github.com/libp2p/go-libp2p-core/network" @@ -78,7 +78,7 @@ func Test_pingRequestHandler_handle(t *testing.T) { defer ctrl.Finish() logger := log.NewLogger("test.subproto") - dummyBlockHash, _ := enc.B58Decode("v6zbuQ4aVSdbTwQhaiZGp5pcL5uL55X3kt2wfxor5W6") + dummyBlockHash, _ := base58.Decode("v6zbuQ4aVSdbTwQhaiZGp5pcL5uL55X3kt2wfxor5W6") var dummyPeerID, _ = types.IDB58Decode("16Uiu2HAmN5YU8V2LnTy9neuuJCLNsxLnd5xVSRZqkjvZUHS3mLoD") type args struct { diff --git a/p2p/subproto/raftstub.go b/p2p/subproto/raftstub.go index ed39bd677..baad777db 100644 --- a/p2p/subproto/raftstub.go +++ b/p2p/subproto/raftstub.go @@ -7,7 +7,7 @@ package subproto import ( "github.com/aergoio/aergo-lib/log" - "github.com/aergoio/aergo/v2/internal/enc" + "github.com/aergoio/aergo/v2/internal/enc/base58" "github.com/aergoio/aergo/v2/p2p/p2pcommon" "github.com/aergoio/aergo/v2/p2p/p2putil" "github.com/aergoio/aergo/v2/types" @@ -69,7 +69,7 @@ func (bh *raftNewBlkNoticeDiscardHandler) Handle(msg p2pcommon.Message, msgBody if blockID, err := types.ParseToBlockID(data.BlockHash); err != nil { // TODO Add penalty score and break - bh.logger.Info().Str(p2putil.LogPeerName, remotePeer.Name()).Str("hash", enc.B58Encode(data.BlockHash)).Msg("malformed blockHash") + bh.logger.Info().Str(p2putil.LogPeerName, remotePeer.Name()).Str("hash", base58.Encode(data.BlockHash)).Msg("malformed blockHash") return } else { // just update last status diff --git a/p2p/subproto/tx.go b/p2p/subproto/tx.go index 094dad100..f3ef230cd 100644 --- a/p2p/subproto/tx.go +++ b/p2p/subproto/tx.go @@ -7,7 +7,7 @@ package subproto import ( "github.com/aergoio/aergo-lib/log" - "github.com/aergoio/aergo/v2/internal/enc" + "github.com/aergoio/aergo/v2/internal/enc/base58" "github.com/aergoio/aergo/v2/message" "github.com/aergoio/aergo/v2/p2p/p2pcommon" "github.com/aergoio/aergo/v2/p2p/p2putil" @@ -107,7 +107,7 @@ func (th *newTxNoticeHandler) Handle(msg p2pcommon.Message, msgBody p2pcommon.Me hashes := make([]types.TxID, len(data.TxHashes)) for i, hash := range data.TxHashes { if tid, err := types.ParseToTxID(hash); err != nil { - th.logger.Info().Str(p2putil.LogPeerName, remotePeer.Name()).Str("hash", enc.B58Encode(hash)).Msg("malformed txhash found") + th.logger.Info().Str(p2putil.LogPeerName, remotePeer.Name()).Str("hash", base58.Encode(hash)).Msg("malformed txhash found") // TODO Add penalty score and break break } else { diff --git a/p2p/subproto/tx_test.go b/p2p/subproto/tx_test.go index 0ab700b24..8b3e09aba 100644 --- a/p2p/subproto/tx_test.go +++ b/p2p/subproto/tx_test.go @@ -10,7 +10,7 @@ import ( "time" "github.com/aergoio/aergo-lib/log" - "github.com/aergoio/aergo/v2/internal/enc" + "github.com/aergoio/aergo/v2/internal/enc/base58" "github.com/aergoio/aergo/v2/message" "github.com/aergoio/aergo/v2/p2p/p2pmock" "github.com/aergoio/aergo/v2/types" @@ -45,7 +45,7 @@ func BenchmarkArrayKey(b *testing.B) { fmt.Printf("P2 in base64\n") target2 := make(map[string]int) for i := 0; i < size; i++ { - target2[enc.B58Encode(samples[i][:])] = i + target2[base58.Encode(samples[i][:])] = i } endTime := time.Now() fmt.Printf("Takes %f sec\n", endTime.Sub(startTime).Seconds()) diff --git a/p2p/synctx_test.go b/p2p/synctx_test.go index 37270baa5..5e79a27f6 100644 --- a/p2p/synctx_test.go +++ b/p2p/synctx_test.go @@ -8,7 +8,7 @@ import ( "time" "github.com/aergoio/aergo-lib/log" - "github.com/aergoio/aergo/v2/internal/enc" + "github.com/aergoio/aergo/v2/internal/enc/base58" "github.com/aergoio/aergo/v2/message" "github.com/aergoio/aergo/v2/message/messagemock" "github.com/aergoio/aergo/v2/p2p/p2pcommon" @@ -285,7 +285,7 @@ func Test_txSyncManager_refineFrontCacheConsumption(t *testing.T) { } } if w == nil { - t.Fatalf("unexpected sent request %v", enc.B58Encode(hashes[i])) + t.Fatalf("unexpected sent request %v", base58.Encode(hashes[i])) } wTids := w.txIDs if len(hashes) != len(wTids) { @@ -422,7 +422,7 @@ func Test_txSyncManager_refineFrontCache(t *testing.T) { } } if !found { - t.Errorf("req hash %v, is not in wanted hash %v", enc.B58Encode(hash), tt.wantSend) + t.Errorf("req hash %v, is not in wanted hash %v", base58.Encode(hash), tt.wantSend) } sentMap[types.ToTxID(hash)] = 1 } @@ -583,7 +583,7 @@ func Test_syncTxManager_handleTxReq(t *testing.T) { var sampleTxs = make([][]byte, len(sampleTxsB58)) var sampleTxHashes = make([]types.TxID, len(sampleTxsB58)) for i, hashb58 := range sampleTxsB58 { - hash, _ := enc.B58Decode(hashb58) + hash, _ := base58.Decode(hashb58) sampleTxs[i] = hash copy(sampleTxHashes[i][:], hash) } diff --git a/p2p/transport/networktransport_test.go b/p2p/transport/networktransport_test.go index 98bf32edf..0209773c8 100644 --- a/p2p/transport/networktransport_test.go +++ b/p2p/transport/networktransport_test.go @@ -12,7 +12,7 @@ import ( "github.com/aergoio/aergo-lib/log" "github.com/aergoio/aergo/v2/config" cfg "github.com/aergoio/aergo/v2/config" - "github.com/aergoio/aergo/v2/internal/enc" + "github.com/aergoio/aergo/v2/internal/enc/hex" "github.com/aergoio/aergo/v2/message" "github.com/aergoio/aergo/v2/p2p/p2pcommon" "github.com/aergoio/aergo/v2/p2p/p2pkey" @@ -35,7 +35,7 @@ func init() { // TODO split this test into two... one is to attempt make connection and the other is test peermanager if same peerid is given // Ignoring test for now, for lack of abstraction on AergoPeer struct func IgnoredTestP2PServiceRunAddPeer(t *testing.T) { - var sampleBlockHash, _ = enc.HexDecode("4f461d85e869ade8a0544f8313987c33a9c06534e50c4ad941498299579bd7ac") + var sampleBlockHash, _ = hex.Decode("4f461d85e869ade8a0544f8313987c33a9c06534e50c4ad941498299579bd7ac") var sampleBlockHeight uint64 = 100215 ctrl := gomock.NewController(t) diff --git a/p2p/txreceiver.go b/p2p/txreceiver.go index d56addf5e..47f77f498 100644 --- a/p2p/txreceiver.go +++ b/p2p/txreceiver.go @@ -10,7 +10,7 @@ import ( "time" "github.com/aergoio/aergo-lib/log" - "github.com/aergoio/aergo/v2/internal/enc" + "github.com/aergoio/aergo/v2/internal/enc/base58" "github.com/aergoio/aergo/v2/message" "github.com/aergoio/aergo/v2/p2p/p2pcommon" "github.com/aergoio/aergo/v2/p2p/p2putil" @@ -116,7 +116,7 @@ func (br *GetTxsReceiver) handleInWaiting(msg p2pcommon.Message, msgBody p2pcomm } // missing tx for !bytes.Equal(br.hashes[br.offset], tx.Hash) { - br.logger.Trace().Str("expect", enc.B58Encode(br.hashes[br.offset])).Str("received", enc.B58Encode(tx.Hash)).Int("offset", br.offset).Msg("expected hash was missing") + br.logger.Trace().Str("expect", base58.Encode(br.hashes[br.offset])).Str("received", base58.Encode(tx.Hash)).Int("offset", br.offset).Msg("expected hash was missing") br.missed = append(br.missed, tx.Hash) br.offset++ if br.offset >= len(br.hashes) { diff --git a/p2p/v030/v030handshake_test.go b/p2p/v030/v030handshake_test.go index b8aa23123..109d52c48 100644 --- a/p2p/v030/v030handshake_test.go +++ b/p2p/v030/v030handshake_test.go @@ -13,7 +13,7 @@ import ( "github.com/aergoio/aergo-lib/log" "github.com/aergoio/aergo/v2/config" - "github.com/aergoio/aergo/v2/internal/enc" + "github.com/aergoio/aergo/v2/internal/enc/hex" "github.com/aergoio/aergo/v2/p2p/p2pcommon" "github.com/aergoio/aergo/v2/p2p/p2pkey" "github.com/aergoio/aergo/v2/p2p/p2pmock" @@ -30,7 +30,7 @@ var ( myChainID, newVerChainID, theirChainID *types.ChainID myChainBytes, newVerChainBytes, theirChainBytes []byte samplePeerID, _ = types.IDB58Decode("16Uiu2HAmFqptXPfcdaCdwipB2fhHATgKGVFVPehDAPZsDKSU7jRm") - dummyBlockHash, _ = enc.HexDecode("4f461d85e869ade8a0544f8313987c33a9c06534e50c4ad941498299579bd7ac") + dummyBlockHash, _ = hex.Decode("4f461d85e869ade8a0544f8313987c33a9c06534e50c4ad941498299579bd7ac") dummyBlockHeight uint64 = 100215 ) diff --git a/p2p/v030/v030io_test.go b/p2p/v030/v030io_test.go index 4a0929d2d..25ff18d51 100644 --- a/p2p/v030/v030io_test.go +++ b/p2p/v030/v030io_test.go @@ -13,7 +13,7 @@ import ( "testing" "time" - "github.com/aergoio/aergo/v2/internal/enc" + "github.com/aergoio/aergo/v2/internal/enc/base58" "github.com/aergoio/aergo/v2/p2p/p2pcommon" "github.com/aergoio/aergo/v2/types" "github.com/gofrs/uuid" @@ -48,7 +48,7 @@ func init() { sampleTxs = make([][]byte, len(sampleTxsB58)) sampleTxHashes = make([]types.TxID, len(sampleTxsB58)) for i, hashb58 := range sampleTxsB58 { - hash, _ := enc.B58Decode(hashb58) + hash, _ := base58.Decode(hashb58) sampleTxs[i] = hash copy(sampleTxHashes[i][:], hash) } @@ -56,7 +56,7 @@ func init() { sampleBlks = make([][]byte, len(sampleBlksB58)) sampleBlksHashes = make([]types.BlockID, len(sampleBlksB58)) for i, hashb58 := range sampleTxsB58 { - hash, _ := enc.B58Decode(hashb58) + hash, _ := base58.Decode(hashb58) sampleBlks[i] = hash copy(sampleBlksHashes[i][:], hash) } diff --git a/p2p/v030/v032handshake.go b/p2p/v030/v032handshake.go index 9234c63f3..a612a22f0 100644 --- a/p2p/v030/v032handshake.go +++ b/p2p/v030/v032handshake.go @@ -12,7 +12,7 @@ import ( "io" "github.com/aergoio/aergo-lib/log" - "github.com/aergoio/aergo/v2/internal/enc" + "github.com/aergoio/aergo/v2/internal/enc/base58" "github.com/aergoio/aergo/v2/p2p/p2pcommon" "github.com/aergoio/aergo/v2/p2p/p2putil" "github.com/aergoio/aergo/v2/types" @@ -47,7 +47,7 @@ func (h *V032Handshaker) checkRemoteStatus(remotePeerStatus *types.Status) error genHash := h.localGenesisHash if !bytes.Equal(genHash, remotePeerStatus.Genesis) { h.sendGoAway("different genesis block") - return fmt.Errorf("different genesis block local: %v , remote %v", enc.B58Encode(genHash), enc.B58Encode(remotePeerStatus.Genesis)) + return fmt.Errorf("different genesis block local: %v , remote %v", base58.Encode(genHash), base58.Encode(remotePeerStatus.Genesis)) } return nil diff --git a/p2p/v030/v033handshake.go b/p2p/v030/v033handshake.go index 513c522b6..4106e258d 100644 --- a/p2p/v030/v033handshake.go +++ b/p2p/v030/v033handshake.go @@ -12,7 +12,7 @@ import ( "io" "github.com/aergoio/aergo-lib/log" - "github.com/aergoio/aergo/v2/internal/enc" + "github.com/aergoio/aergo/v2/internal/enc/base58" "github.com/aergoio/aergo/v2/internal/network" "github.com/aergoio/aergo/v2/p2p/p2pcommon" "github.com/aergoio/aergo/v2/p2p/p2putil" @@ -76,7 +76,7 @@ func (h *V033Handshaker) checkRemoteStatus(remotePeerStatus *types.Status) error genHash := h.localGenesisHash if !bytes.Equal(genHash, remotePeerStatus.Genesis) { h.sendGoAway("different genesis block") - return fmt.Errorf("different genesis block local: %v , remote %v", enc.B58Encode(genHash), enc.B58Encode(remotePeerStatus.Genesis)) + return fmt.Errorf("different genesis block local: %v , remote %v", base58.Encode(genHash), base58.Encode(remotePeerStatus.Genesis)) } return nil diff --git a/p2p/v200/v200handshake.go b/p2p/v200/v200handshake.go index d9f23c140..422ed2961 100644 --- a/p2p/v200/v200handshake.go +++ b/p2p/v200/v200handshake.go @@ -14,7 +14,7 @@ import ( "time" "github.com/aergoio/aergo-lib/log" - "github.com/aergoio/aergo/v2/internal/enc" + "github.com/aergoio/aergo/v2/internal/enc/base58" "github.com/aergoio/aergo/v2/internal/network" "github.com/aergoio/aergo/v2/p2p/p2pcommon" "github.com/aergoio/aergo/v2/p2p/p2pkey" @@ -192,7 +192,7 @@ func (h *V200Handshaker) checkRemoteStatus(remotePeerStatus *types.Status) error genHash := h.localGenesisHash if !bytes.Equal(genHash, remotePeerStatus.Genesis) { h.sendGoAway("different genesis block") - return fmt.Errorf("different genesis block local: %v , remote %v", enc.B58Encode(genHash), enc.B58Encode(remotePeerStatus.Genesis)) + return fmt.Errorf("different genesis block local: %v , remote %v", base58.Encode(genHash), base58.Encode(remotePeerStatus.Genesis)) } h.remoteMeta = rMeta diff --git a/p2p/v200/v200handshake_test.go b/p2p/v200/v200handshake_test.go index 1d446c6d5..283ec7846 100644 --- a/p2p/v200/v200handshake_test.go +++ b/p2p/v200/v200handshake_test.go @@ -16,7 +16,7 @@ import ( "github.com/aergoio/aergo-lib/log" "github.com/aergoio/aergo/v2/config" - "github.com/aergoio/aergo/v2/internal/enc" + "github.com/aergoio/aergo/v2/internal/enc/hex" "github.com/aergoio/aergo/v2/p2p/p2pcommon" "github.com/aergoio/aergo/v2/p2p/p2pkey" "github.com/aergoio/aergo/v2/p2p/p2pmock" @@ -35,7 +35,7 @@ var ( theirChainBytes []byte samplePeerID, _ = types.IDB58Decode("16Uiu2HAmFqptXPfcdaCdwipB2fhHATgKGVFVPehDAPZsDKSU7jRm") - dummyBlockHash, _ = enc.HexDecode("4f461d85e869ade8a0544f8313987c33a9c06534e50c4ad941498299579bd7ac") + dummyBlockHash, _ = hex.Decode("4f461d85e869ade8a0544f8313987c33a9c06534e50c4ad941498299579bd7ac") dummyBlockID = types.MustParseBlockID(dummyBlockHash) dummyBlockHeight uint64 = 100215 diff --git a/rpc/grpcserver_test.go b/rpc/grpcserver_test.go index e0a961de9..f0aad80b9 100644 --- a/rpc/grpcserver_test.go +++ b/rpc/grpcserver_test.go @@ -12,7 +12,9 @@ import ( "testing" "github.com/aergoio/aergo-actor/actor" - "github.com/aergoio/aergo/v2/internal/enc" + "github.com/aergoio/aergo/v2/internal/enc/base58" + "github.com/aergoio/aergo/v2/internal/enc/base64" + "github.com/aergoio/aergo/v2/internal/enc/hex" "github.com/aergoio/aergo/v2/message" "github.com/aergoio/aergo/v2/message/messagemock" "github.com/aergoio/aergo/v2/p2p/p2pcommon" @@ -24,37 +26,37 @@ import ( func TestAergoRPCService_dummys(t *testing.T) { fmt.Println("dummyBlockHash") - fmt.Printf("HEX : %s \n", enc.HexEncode(dummyBlockHash)) - fmt.Printf("B64 : %s \n", enc.B64Encode(dummyBlockHash)) - fmt.Printf("B58 : %s \n", enc.B58Encode(dummyBlockHash)) + fmt.Printf("HEX : %s \n", hex.Encode(dummyBlockHash)) + fmt.Printf("B64 : %s \n", base64.Encode(dummyBlockHash)) + fmt.Printf("B58 : %s \n", base58.Encode(dummyBlockHash)) fmt.Println() fmt.Println("dummyTx") - fmt.Printf("HEX : %s \n", enc.HexEncode(dummyTxHash)) - fmt.Printf("B64 : %s \n", enc.B64Encode(dummyTxHash)) - fmt.Printf("B58 : %s \n", enc.B58Encode(dummyTxHash)) + fmt.Printf("HEX : %s \n", hex.Encode(dummyTxHash)) + fmt.Printf("B64 : %s \n", base64.Encode(dummyTxHash)) + fmt.Printf("B58 : %s \n", base58.Encode(dummyTxHash)) fmt.Println() fmt.Println("Address1") - fmt.Printf("HEX : %s \n", enc.HexEncode(dummyWalletAddress)) - fmt.Printf("B64 : %s \n", enc.B64Encode(dummyWalletAddress)) - fmt.Printf("B58 : %s \n", enc.B58Encode(dummyWalletAddress)) + fmt.Printf("HEX : %s \n", hex.Encode(dummyWalletAddress)) + fmt.Printf("B64 : %s \n", base64.Encode(dummyWalletAddress)) + fmt.Printf("B58 : %s \n", base58.Encode(dummyWalletAddress)) fmt.Println() fmt.Println("Address2") - fmt.Printf("HEX : %s \n", enc.HexEncode(dummyWalletAddress2)) - fmt.Printf("B64 : %s \n", enc.B64Encode(dummyWalletAddress2)) - fmt.Printf("B58 : %s \n", enc.B58Encode(dummyWalletAddress2)) + fmt.Printf("HEX : %s \n", hex.Encode(dummyWalletAddress2)) + fmt.Printf("B64 : %s \n", base64.Encode(dummyWalletAddress2)) + fmt.Printf("B58 : %s \n", base58.Encode(dummyWalletAddress2)) fmt.Println() } -var dummyBlockHash, _ = enc.HexDecode("4f461d85e869ade8a0544f8313987c33a9c06534e50c4ad941498299579bd7ac") +var dummyBlockHash, _ = hex.Decode("4f461d85e869ade8a0544f8313987c33a9c06534e50c4ad941498299579bd7ac") var dummyBlockHeight uint32 = 100215 -var dummyTxHash, _ = enc.HexDecode("218bdab4e87fb332b55eb89854ef553f9e3d440c81fff4161b672adede1261ee") +var dummyTxHash, _ = hex.Decode("218bdab4e87fb332b55eb89854ef553f9e3d440c81fff4161b672adede1261ee") // base64 encoding of dummyTxHash is "" -var dummyWalletAddress, _ = enc.B58Decode("1Ee8uhLFXzkSRRU1orBpgXFAPpVi64aSYo") -var dummyWalletAddress2, _ = enc.B58Decode("16Uiu2HAkwgfFvViH6j2QpQYKtGKKdveEKZvU2T5mRkqFLTZKU4Vp") +var dummyWalletAddress, _ = base58.Decode("1Ee8uhLFXzkSRRU1orBpgXFAPpVi64aSYo") +var dummyWalletAddress2, _ = base58.Decode("16Uiu2HAkwgfFvViH6j2QpQYKtGKKdveEKZvU2T5mRkqFLTZKU4Vp") var dummyPayload = []byte("OPreturn I am groooot") var hubStub *component.ComponentHub diff --git a/state/chainstatedb.go b/state/chainstatedb.go index a5ade484c..4dbf83c7d 100644 --- a/state/chainstatedb.go +++ b/state/chainstatedb.go @@ -7,7 +7,7 @@ import ( "github.com/aergoio/aergo-lib/db" "github.com/aergoio/aergo/v2/internal/common" - "github.com/aergoio/aergo/v2/internal/enc" + "github.com/aergoio/aergo/v2/internal/enc/base58" "github.com/aergoio/aergo/v2/types" ) @@ -168,8 +168,8 @@ func (sdb *ChainStateDB) UpdateRoot(bstate *BlockState) error { // bstate.BlockInfo.StateRoot = types.ToHashID(sdb.GetRoot()) // } - logger.Debug().Str("before", enc.B58Encode(sdb.states.GetRoot())). - Str("stateRoot", enc.B58Encode(bstate.GetRoot())).Msg("apply block state") + logger.Debug().Str("before", base58.Encode(sdb.states.GetRoot())). + Str("stateRoot", base58.Encode(bstate.GetRoot())).Msg("apply block state") if err := sdb.states.SetRoot(bstate.GetRoot()); err != nil { return err @@ -182,8 +182,8 @@ func (sdb *ChainStateDB) SetRoot(targetBlockRoot []byte) error { sdb.Lock() defer sdb.Unlock() - logger.Debug().Str("before", enc.B58Encode(sdb.states.GetRoot())). - Str("target", enc.B58Encode(targetBlockRoot)).Msg("rollback state") + logger.Debug().Str("before", base58.Encode(sdb.states.GetRoot())). + Str("target", base58.Encode(targetBlockRoot)).Msg("rollback state") sdb.states.SetRoot(targetBlockRoot) return nil diff --git a/state/statebuffer_test.go b/state/statebuffer_test.go index ceb9c6ea5..56d65c1ae 100644 --- a/state/statebuffer_test.go +++ b/state/statebuffer_test.go @@ -3,7 +3,7 @@ package state import ( "testing" - "github.com/aergoio/aergo/v2/internal/enc" + "github.com/aergoio/aergo/v2/internal/enc/hex" "github.com/aergoio/aergo/v2/types" "github.com/stretchr/testify/assert" ) @@ -26,7 +26,7 @@ func TestBufferIndexStack(t *testing.T) { idxs.push(k0, 4) idxs.push(k1, 5) for i, v := range kset { - t.Logf("(%d)[%v]%v", i, enc.HexEncode(v[:]), idxs[v]) + t.Logf("(%d)[%v]%v", i, hex.Encode(v[:]), idxs[v]) } assert.Equal(t, 4, idxs.pop(k0)) @@ -39,13 +39,13 @@ func TestBufferIndexStack(t *testing.T) { assert.Equal(t, 2, idxs.peek(k1)) assert.Equal(t, 2, idxs.pop(k1)) for i, v := range kset { - t.Logf("(%d)[%v]%v", i, enc.HexEncode(v[:]), idxs[v]) + t.Logf("(%d)[%v]%v", i, hex.Encode(v[:]), idxs[v]) } idxs.push(k0, 6, 8, 12) idxs.push(k1, 7, 9, 10, 11) for i, v := range kset { - t.Logf("(%d)[%v]%v", i, enc.HexEncode(v[:]), idxs[v]) + t.Logf("(%d)[%v]%v", i, hex.Encode(v[:]), idxs[v]) } assert.Equal(t, 12, idxs[k0].peek()) @@ -57,7 +57,7 @@ func TestBufferIndexRollback(t *testing.T) { idxs.push(k0, 0, 1, 3, 4, 6, 7, 8) idxs.push(k1, 2, 5, 9) for i, v := range kset { - t.Logf("(%d)[%v]%v", i, enc.HexEncode(v[:]), idxs[v]) + t.Logf("(%d)[%v]%v", i, hex.Encode(v[:]), idxs[v]) } assert.Equal(t, 8, idxs[k0].peek()) @@ -65,7 +65,7 @@ func TestBufferIndexRollback(t *testing.T) { idxs.rollback(5) for i, v := range kset { - t.Logf("(%d)[%v]%v", i, enc.HexEncode(v[:]), idxs[v]) + t.Logf("(%d)[%v]%v", i, hex.Encode(v[:]), idxs[v]) } assert.Equal(t, 4, idxs[k0].peek()) @@ -73,7 +73,7 @@ func TestBufferIndexRollback(t *testing.T) { idxs.rollback(0) for i, v := range kset { - t.Logf("(%d)[%v]%v", i, enc.HexEncode(v[:]), idxs[v]) + t.Logf("(%d)[%v]%v", i, hex.Encode(v[:]), idxs[v]) } assert.Equal(t, -1, idxs[k0].peek()) diff --git a/state/statedata.go b/state/statedata.go index 1f727bda5..5522ce125 100644 --- a/state/statedata.go +++ b/state/statedata.go @@ -2,7 +2,7 @@ package state import ( "github.com/aergoio/aergo-lib/db" - "github.com/aergoio/aergo/v2/internal/enc" + "github.com/aergoio/aergo/v2/internal/enc/gob" "github.com/aergoio/aergo/v2/types" "github.com/golang/protobuf/proto" ) @@ -22,7 +22,7 @@ func saveData(store db.DB, key []byte, data interface{}) error { return err } default: - raw, err = enc.GobEncode(data) + raw, err = gob.Encode(data) if err != nil { return err } @@ -47,7 +47,7 @@ func loadData(store db.DB, key []byte, data interface{}) error { case proto.Message: err = proto.Unmarshal(raw, data.(proto.Message)) default: - err = enc.GobDecode(raw, data) + err = gob.Decode(raw, data) } return err } diff --git a/state/statedb.go b/state/statedb.go index 213e1a007..eefd82874 100644 --- a/state/statedb.go +++ b/state/statedb.go @@ -15,7 +15,7 @@ import ( "github.com/aergoio/aergo-lib/db" "github.com/aergoio/aergo-lib/log" "github.com/aergoio/aergo/v2/internal/common" - "github.com/aergoio/aergo/v2/internal/enc" + "github.com/aergoio/aergo/v2/internal/enc/base58" "github.com/aergoio/aergo/v2/pkg/trie" "github.com/aergoio/aergo/v2/types" ) @@ -401,7 +401,7 @@ func (states *StateDB) GetVarAndProof(id []byte, root []byte, compressed bool) ( Height: uint32(height), AuditPath: ap, } - logger.Debug().Str("contract root : ", enc.B58Encode(root)).Msg("Get contract variable and Proof") + logger.Debug().Str("contract root : ", base58.Encode(root)).Msg("Get contract variable and Proof") return contractVarProof, nil } @@ -431,7 +431,7 @@ func (states *StateDB) GetAccountAndProof(id []byte, root []byte, compressed boo Height: uint32(height), AuditPath: ap, } - logger.Debug().Str("state root : ", enc.B58Encode(root)).Msg("Get Account and Proof") + logger.Debug().Str("state root : ", base58.Encode(root)).Msg("Get Account and Proof") return accountProof, nil } @@ -553,7 +553,7 @@ func (states *StateDB) HasMarker(root []byte) bool { } marker := states.store.Get(common.Hasher(root)) if marker != nil && bytes.Equal(marker, stateMarker) { - // logger.Debug().Str("stateRoot", enc.ToString(root)).Str("marker", enc.HexEncode(marker)).Msg("IsMarked") + // logger.Debug().Str("stateRoot", enc.ToString(root)).Str("marker", hex.HexEncode(marker)).Msg("IsMarked") return true } return false diff --git a/state/storage.go b/state/storage.go index f7ed9e6aa..03d8dd433 100644 --- a/state/storage.go +++ b/state/storage.go @@ -6,7 +6,7 @@ import ( "github.com/aergoio/aergo-lib/db" "github.com/aergoio/aergo/v2/internal/common" - "github.com/aergoio/aergo/v2/internal/enc" + "github.com/aergoio/aergo/v2/internal/enc/base58" "github.com/aergoio/aergo/v2/pkg/trie" "github.com/aergoio/aergo/v2/types" ) @@ -134,8 +134,8 @@ func (storage *bufferedStorage) update() error { return err } if !bytes.Equal(before, storage.trie.Root) { - logger.Debug().Str("before", enc.B58Encode(before)). - Str("after", enc.B58Encode(storage.trie.Root)).Msg("Changed storage trie root") + logger.Debug().Str("before", base58.Encode(before)). + Str("after", base58.Encode(storage.trie.Root)).Msg("Changed storage trie root") storage.dirty = true } return nil diff --git a/syncer/blockfetcher.go b/syncer/blockfetcher.go index 92d6016fc..9e6c1d541 100644 --- a/syncer/blockfetcher.go +++ b/syncer/blockfetcher.go @@ -9,7 +9,7 @@ import ( "sync/atomic" "time" - "github.com/aergoio/aergo/v2/internal/enc" + "github.com/aergoio/aergo/v2/internal/enc/base58" "github.com/aergoio/aergo/v2/message" "github.com/aergoio/aergo/v2/pkg/component" "github.com/aergoio/aergo/v2/types" @@ -342,7 +342,7 @@ func (bf *BlockFetcher) checkTaskTimeout() error { return err } - logger.Error().Uint64("StartNo", task.startNo).Str("start", enc.B58Encode(task.hashes[0])).Int("cout", task.count).Int("runqueue", bf.runningQueue.Len()).Int("pendingqueue", bf.pendingQueue.Len()). + logger.Error().Uint64("StartNo", task.startNo).Str("start", base58.Encode(task.hashes[0])).Int("cout", task.count).Int("runqueue", bf.runningQueue.Len()).Int("pendingqueue", bf.pendingQueue.Len()). Msg("timeouted task pushed to pending queue") //time.Sleep(10000*time.Second) @@ -358,7 +358,7 @@ func (bf *BlockFetcher) processFailedTask(task *FetchTask, isErr bool) error { } } - logger.Error().Int("peerno", task.syncPeer.No).Uint64("StartNo", task.startNo).Str("start", enc.B58Encode(task.hashes[0])).Msg("task fail, move to retry queue") + logger.Error().Int("peerno", task.syncPeer.No).Uint64("StartNo", task.startNo).Str("start", base58.Encode(task.hashes[0])).Msg("task fail, move to retry queue") failPeer := task.syncPeer @@ -380,7 +380,7 @@ func (bf *BlockFetcher) processFailedTask(task *FetchTask, isErr bool) error { } func (bf *BlockFetcher) popNextTask(task *FetchTask) { - logger.Debug().Int("retry", task.retry).Uint64("StartNo", task.startNo).Str("start", enc.B58Encode(task.hashes[0])).Str("end", enc.B58Encode(task.hashes[task.count-1])). + logger.Debug().Int("retry", task.retry).Uint64("StartNo", task.startNo).Str("start", base58.Encode(task.hashes[0])).Str("end", base58.Encode(task.hashes[task.count-1])). Int("tasks retry", bf.retryQueue.Len()).Int("tasks pending", bf.pendingQueue.Len()).Msg("next fetchtask") var poppedTask *FetchTask @@ -427,7 +427,7 @@ func (bf *BlockFetcher) searchCandidateTask() (*FetchTask, error) { start, end := 0, 0 count := hashSet.Count - logger.Debug().Uint64("startno", hashSet.StartNo).Str("start", enc.B58Encode(hashSet.Hashes[0])).Int("count", hashSet.Count).Msg("add new fetchtasks from HashSet") + logger.Debug().Uint64("startno", hashSet.StartNo).Str("start", base58.Encode(hashSet.Hashes[0])).Int("count", hashSet.Count).Msg("add new fetchtasks from HashSet") for start < count { end = start + bf.maxFetchSize @@ -464,7 +464,7 @@ func (bf *BlockFetcher) searchCandidateTask() (*FetchTask, error) { return nil, nil } - logger.Debug().Uint64("startno", hashSet.StartNo).Array("hashes", &LogBlockHashesMarshaller{hashSet.Hashes, 10}).Str("start", enc.B58Encode(hashSet.Hashes[0])).Int("count", hashSet.Count).Msg("BlockFetcher got hashset") + logger.Debug().Uint64("startno", hashSet.StartNo).Array("hashes", &LogBlockHashesMarshaller{hashSet.Hashes, 10}).Str("start", base58.Encode(hashSet.Hashes[0])).Int("count", hashSet.Count).Msg("BlockFetcher got hashset") bf.curHashSet = hashSet addNewFetchTasks(hashSet) @@ -488,12 +488,12 @@ func (m LogBlockHashesMarshaller) MarshalZerologArray(a *zerolog.Array) { size := len(m.arr) if size > m.limit { for i := 0; i < m.limit-1; i++ { - a.Str(enc.B58Encode(m.arr[i])) + a.Str(base58.Encode(m.arr[i])) } a.Str(fmt.Sprintf("(and %d more)", size-m.limit+1)) } else { for _, element := range m.arr { - a.Str(enc.B58Encode(element)) + a.Str(base58.Encode(element)) } } } @@ -533,7 +533,7 @@ func (bf *BlockFetcher) runTask(task *FetchTask, peer *SyncPeer) { task.syncPeer = peer bf.runningQueue.PushBack(task) - logger.Debug().Int("peerno", task.syncPeer.No).Int("count", task.count).Uint64("StartNo", task.startNo).Str("start", enc.B58Encode(task.hashes[0])).Int("runqueue", bf.runningQueue.Len()).Msg("send block fetch request") + logger.Debug().Int("peerno", task.syncPeer.No).Int("count", task.count).Uint64("StartNo", task.startNo).Str("start", base58.Encode(task.hashes[0])).Int("runqueue", bf.runningQueue.Len()).Msg("send block fetch request") bf.compRequester.TellTo(message.P2PSvc, &message.GetBlockChunks{Seq: bf.GetSeq(), GetBlockInfos: message.GetBlockInfos{ToWhom: peer.ID, Hashes: task.hashes}, TTL: DfltFetchTimeOut}) } @@ -553,7 +553,7 @@ func (bf *BlockFetcher) findFinished(msg *message.GetBlockChunksRsp, peerMatch b if task.isPeerMatched(msg.ToWhom) { bf.runningQueue.Remove(e) - logger.Debug().Stringer("peer", types.LogPeerShort(msg.ToWhom)).Err(msg.Err).Str("start", enc.B58Encode(task.hashes[0])).Int("count", task.count).Int("runqueue", bf.runningQueue.Len()).Msg("task finished with error") + logger.Debug().Stringer("peer", types.LogPeerShort(msg.ToWhom)).Err(msg.Err).Str("start", base58.Encode(task.hashes[0])).Int("count", task.count).Int("runqueue", bf.runningQueue.Len()).Msg("task finished with error") return task, nil } } else { @@ -561,7 +561,7 @@ func (bf *BlockFetcher) findFinished(msg *message.GetBlockChunksRsp, peerMatch b if task.isMatched(msg.ToWhom, msg.Blocks, count) { bf.runningQueue.Remove(e) - logger.Debug().Uint64("StartNo", task.startNo).Str("start", enc.B58Encode(task.hashes[0])).Int("count", task.count).Int("runqueue", bf.runningQueue.Len()). + logger.Debug().Uint64("StartNo", task.startNo).Str("start", base58.Encode(task.hashes[0])).Int("count", task.count).Int("runqueue", bf.runningQueue.Len()). Msg("task finished") return task, nil @@ -737,7 +737,7 @@ func (tq *TaskQueue) Peek() *FetchTask { func (task *FetchTask) isTimeOut(now time.Time, timeout time.Duration) bool { if now.Sub(task.started) > timeout { - logger.Info().Int("peerno", task.syncPeer.No).Uint64("startno", task.startNo).Str("start", enc.B58Encode(task.hashes[0])).Int("cout", task.count).Msg("FetchTask peer timeouted") + logger.Info().Int("peerno", task.syncPeer.No).Uint64("startno", task.startNo).Str("start", base58.Encode(task.hashes[0])).Int("cout", task.count).Msg("FetchTask peer timeouted") return true } @@ -756,7 +756,7 @@ func (task *FetchTask) isMatched(peerID types.PeerID, blocks []*types.Block, cou for i, block := range blocks { if bytes.Compare(task.hashes[i], block.GetHash()) != 0 { - logger.Info().Int("peerno", task.syncPeer.No).Str("hash", enc.B58Encode(task.hashes[0])).Int("idx", i).Msg("task hash mismatch") + logger.Info().Int("peerno", task.syncPeer.No).Str("hash", base58.Encode(task.hashes[0])).Int("idx", i).Msg("task hash mismatch") return false } } diff --git a/syncer/blockprocessor.go b/syncer/blockprocessor.go index 4dfc26aef..cac892da5 100644 --- a/syncer/blockprocessor.go +++ b/syncer/blockprocessor.go @@ -6,7 +6,7 @@ import ( "sort" "github.com/aergoio/aergo/v2/chain" - "github.com/aergoio/aergo/v2/internal/enc" + "github.com/aergoio/aergo/v2/internal/enc/base58" "github.com/aergoio/aergo/v2/message" "github.com/aergoio/aergo/v2/pkg/component" "github.com/aergoio/aergo/v2/types" @@ -136,8 +136,8 @@ func (bproc *BlockProcessor) GetBlockChunkRsp(msg *message.GetBlockChunksRsp) er //TODO invalid peer logger.Error().Stringer("peer", types.LogPeerShort(msg.ToWhom)). Int("count", len(msg.Blocks)). - Str("from", enc.B58Encode(msg.Blocks[0].GetHash())). - Str("to", enc.B58Encode(msg.Blocks[len(msg.Blocks)-1].GetHash())). + Str("from", base58.Encode(msg.Blocks[0].GetHash())). + Str("to", base58.Encode(msg.Blocks[len(msg.Blocks)-1].GetHash())). Msg("dropped unknown block response message") return nil } @@ -172,7 +172,7 @@ func (bproc *BlockProcessor) GetBlockChunkRspError(msg *message.GetBlockChunksRs func (bproc *BlockProcessor) AddBlockResponse(msg *message.AddBlockRsp) error { if err := bproc.isValidResponse(msg); err != nil { - logger.Info().Err(err).Uint64("no", msg.BlockNo).Str("hash", enc.B58Encode(msg.BlockHash)).Msg("block connect failed") + logger.Info().Err(err).Uint64("no", msg.BlockNo).Str("hash", base58.Encode(msg.BlockHash)).Msg("block connect failed") return err } @@ -182,12 +182,12 @@ func (bproc *BlockProcessor) AddBlockResponse(msg *message.AddBlockRsp) error { if curNo != msg.BlockNo || !bytes.Equal(curHash, msg.BlockHash) { logger.Error().Uint64("curNo", curNo).Uint64("msgNo", msg.BlockNo). - Str("curHash", enc.B58Encode(curHash)).Str("msgHash", enc.B58Encode(msg.BlockHash)). + Str("curHash", base58.Encode(curHash)).Str("msgHash", base58.Encode(msg.BlockHash)). Msg("invalid add block response") return &ErrSyncMsg{msg: msg, str: "drop unknown add response"} } - logger.Info().Uint64("no", msg.BlockNo).Str("hash", enc.B58Encode(msg.BlockHash)).Msg("block connect succeed") + logger.Info().Uint64("no", msg.BlockNo).Str("hash", base58.Encode(msg.BlockHash)).Msg("block connect succeed") bproc.blockFetcher.stat.setLastAddBlock(curBlock) @@ -266,7 +266,7 @@ func (bproc *BlockProcessor) connectBlock(block *types.Block) { } logger.Info().Uint64("no", block.GetHeader().BlockNo). - Str("hash", enc.B58Encode(block.GetHash())). + Str("hash", base58.Encode(block.GetHash())). Msg("request connecting block to chainsvc") bproc.compRequester.RequestTo(message.ChainSvc, &message.AddBlock{PeerID: "", Block: block, Bstate: nil, IsSync: true}) @@ -283,7 +283,7 @@ func (bproc *BlockProcessor) pushToConnQueue(newReq *ConnectTask) { bproc.connQueue = sortedList logger.Info().Int("len", len(bproc.connQueue)).Uint64("firstno", newReq.firstNo). - Str("firstHash", enc.B58Encode(newReq.Blocks[0].GetHash())). + Str("firstHash", base58.Encode(newReq.Blocks[0].GetHash())). Msg("add new task to connect queue") } @@ -307,7 +307,7 @@ func (bproc *BlockProcessor) popFromConnQueue() *ConnectTask { bproc.connQueue = sortedList logger.Info().Int("len", len(sortedList)).Uint64("firstno", newReq.firstNo). - Str("firstHash", enc.B58Encode(newReq.Blocks[0].GetHash())). + Str("firstHash", base58.Encode(newReq.Blocks[0].GetHash())). Msg("pop task from connect queue") return newReq diff --git a/syncer/finder.go b/syncer/finder.go index d0ab54d65..a99ae1fe9 100644 --- a/syncer/finder.go +++ b/syncer/finder.go @@ -6,7 +6,7 @@ import ( "time" "github.com/aergoio/aergo/v2/chain" - "github.com/aergoio/aergo/v2/internal/enc" + "github.com/aergoio/aergo/v2/internal/enc/base58" "github.com/aergoio/aergo/v2/message" "github.com/aergoio/aergo/v2/pkg/component" "github.com/aergoio/aergo/v2/types" @@ -140,7 +140,7 @@ func (finder *Finder) lightscan() (*types.BlockInfo, error) { if ancestor == nil { logger.Debug().Msg("not found ancestor in lightscan") } else { - logger.Info().Str("hash", enc.B58Encode(ancestor.Hash)).Uint64("no", ancestor.No).Msg("find ancestor in lightscan") + logger.Info().Str("hash", base58.Encode(ancestor.Hash)).Uint64("no", ancestor.No).Msg("find ancestor in lightscan") if ancestor.No >= finder.ctx.TargetNo { logger.Info().Msg("already synchronized") @@ -163,7 +163,7 @@ func (finder *Finder) getAnchors() ([][]byte, error) { finder.ctx.LastAnchor = result.(message.GetAnchorsRsp).LastNo } - logger.Info().Str("start", enc.B58Encode(anchors[0])).Int("count", len(anchors)).Uint64("last", finder.ctx.LastAnchor).Msg("get anchors from chain") + logger.Info().Str("start", base58.Encode(anchors[0])).Int("count", len(anchors)).Uint64("last", finder.ctx.LastAnchor).Msg("get anchors from chain") return anchors, nil } @@ -204,7 +204,7 @@ func (finder *Finder) fullscan() (*types.BlockInfo, error) { if ancestor == nil { logger.Info().Msg("failed to search ancestor in fullscan") } else { - logger.Info().Uint64("no", ancestor.No).Str("hash", enc.B58Encode(ancestor.Hash)).Msg("find ancestor in fullscan") + logger.Info().Uint64("no", ancestor.No).Str("hash", base58.Encode(ancestor.Hash)).Msg("find ancestor in fullscan") } return ancestor, err diff --git a/syncer/hashfetcher.go b/syncer/hashfetcher.go index 66ea2a076..4097b4eae 100644 --- a/syncer/hashfetcher.go +++ b/syncer/hashfetcher.go @@ -4,7 +4,7 @@ import ( "sync" "time" - "github.com/aergoio/aergo/v2/internal/enc" + "github.com/aergoio/aergo/v2/internal/enc/base58" "github.com/aergoio/aergo/v2/message" "github.com/aergoio/aergo/v2/pkg/component" "github.com/aergoio/aergo/v2/types" @@ -171,7 +171,7 @@ func (hf *HashFetcher) requestHashSet() { hf.reqTime = time.Now() hf.isRequesting = true - logger.Debug().Uint64("prev", hf.lastBlockInfo.No).Str("prevhash", enc.B58Encode(hf.lastBlockInfo.Hash)).Uint64("count", count).Msg("request hashset to peer") + logger.Debug().Uint64("prev", hf.lastBlockInfo.No).Str("prevhash", base58.Encode(hf.lastBlockInfo.Hash)).Uint64("count", count).Msg("request hashset to peer") hf.compRequester.TellTo(message.P2PSvc, &message.GetHashes{Seq: hf.GetSeq(), ToWhom: hf.ctx.PeerID, PrevInfo: hf.lastBlockInfo, Count: count}) } @@ -241,8 +241,8 @@ func (hf *HashFetcher) isValidResponse(msg *message.GetHashesRsp) (bool, error) } if !isValid { - logger.Error().Str("req prev", enc.B58Encode(hf.lastBlockInfo.Hash)). - Str("msg prev", enc.B58Encode(msg.PrevInfo.Hash)). + logger.Error().Str("req prev", base58.Encode(hf.lastBlockInfo.Hash)). + Str("msg prev", base58.Encode(msg.PrevInfo.Hash)). Uint64("req count", hf.reqCount). Uint64("msg count", msg.Count). Msg("invalid GetHashesRsp") @@ -267,8 +267,8 @@ func (hf *HashFetcher) GetHahsesRsp(msg *message.GetHashesRsp) { logger.Debug().Int("count", count). Uint64("prev", msg.PrevInfo.No). - Str("start", enc.B58Encode(msg.Hashes[0])). - Str("end", enc.B58Encode(msg.Hashes[count-1])).Msg("receive GetHashesRsp") + Str("start", base58.Encode(msg.Hashes[0])). + Str("end", base58.Encode(msg.Hashes[count-1])).Msg("receive GetHashesRsp") hf.responseCh <- msg return diff --git a/tools/genesisdump/main.go b/tools/genesisdump/main.go index cecbb5f78..030cebe38 100644 --- a/tools/genesisdump/main.go +++ b/tools/genesisdump/main.go @@ -5,7 +5,7 @@ import ( "fmt" "os" - "github.com/aergoio/aergo/v2/internal/enc" + "github.com/aergoio/aergo/v2/internal/enc/hex" "github.com/aergoio/aergo/v2/types" ) @@ -41,6 +41,6 @@ func main() { panic(err) } - str := "\"" + enc.HexEncode(bs) + "\"" + str := "\"" + hex.Encode(bs) + "\"" fmt.Println(str) } diff --git a/types/account.go b/types/account.go index 2c86e8825..ecd58ef70 100644 --- a/types/account.go +++ b/types/account.go @@ -5,7 +5,8 @@ import ( "fmt" "strings" - "github.com/aergoio/aergo/v2/internal/enc" + "github.com/aergoio/aergo/v2/internal/enc/base58check" + "github.com/aergoio/aergo/v2/internal/enc/hex" ) const AddressLength = 33 @@ -49,7 +50,7 @@ func EncodeAddress(addr Address) string { if len(addr) != AddressLength { return string(addr) } - encoded, _ := enc.B58CheckEncode(fmt.Sprintf("%x", AddressVersion), enc.HexEncode(addr)) + encoded, _ := base58check.Encode(fmt.Sprintf("%x", AddressVersion), hex.Encode(addr)) return encoded } @@ -67,11 +68,11 @@ func DecodeAddress(encodedAddr string) (Address, error) { } return []byte(name), nil } - decodedString, err := enc.B58CheckDecode(encodedAddr) + decodedString, err := base58check.Decode(encodedAddr) if err != nil { return nil, err } - decodedBytes, err := enc.HexDecode(decodedString) + decodedBytes, err := hex.Decode(decodedString) if err != nil { return nil, err } @@ -94,16 +95,16 @@ func DecodeAddressBytes(decodedBytes []byte) (Address, error) { } func EncodePrivKey(key []byte) string { - encoded, _ := enc.B58CheckEncode(fmt.Sprintf("%x", PrivKeyVersion), enc.HexEncode(key)) + encoded, _ := base58check.Encode(fmt.Sprintf("%x", PrivKeyVersion), hex.Encode(key)) return encoded } func DecodePrivKey(encodedKey string) ([]byte, error) { - decodedString, err := enc.B58CheckDecode(encodedKey) + decodedString, err := base58check.Decode(encodedKey) if err != nil { return nil, err } - decodedBytes, err := enc.HexDecode(decodedString) + decodedBytes, err := hex.Decode(decodedString) if err != nil { return nil, err } diff --git a/types/blockchain.go b/types/blockchain.go index 6cd7f9131..27c938df4 100644 --- a/types/blockchain.go +++ b/types/blockchain.go @@ -17,7 +17,7 @@ import ( "time" "github.com/aergoio/aergo/v2/internal/common" - "github.com/aergoio/aergo/v2/internal/enc" + "github.com/aergoio/aergo/v2/internal/enc/base58" "github.com/aergoio/aergo/v2/internal/merkle" "github.com/golang/protobuf/proto" "github.com/libp2p/go-libp2p-core/crypto" @@ -452,14 +452,14 @@ func (block *Block) BPID2Str() string { return "" } - return enc.B58Encode([]byte(id)) + return base58.Encode([]byte(id)) } // ID returns the base64 encoded formated ID (hash) of block. func (block *Block) ID() string { hash := block.BlockHash() if hash != nil { - return enc.B58Encode(hash) + return base58.Encode(hash) } return "" @@ -470,7 +470,7 @@ func (block *Block) ID() string { func (block *Block) PrevID() string { hash := block.GetHeader().GetPrevBlockHash() if hash != nil { - return enc.B58Encode(hash) + return base58.Encode(hash) } return "" diff --git a/types/common.go b/types/common.go index 783290cbd..8304b2e48 100644 --- a/types/common.go +++ b/types/common.go @@ -1,7 +1,8 @@ package types import ( - "github.com/aergoio/aergo/v2/internal/enc" + "github.com/aergoio/aergo/v2/internal/enc/base58" + "github.com/aergoio/aergo/v2/internal/enc/base64" ) const MAXBLOCKNO BlockNo = 18446744073709551615 @@ -9,20 +10,20 @@ const maxMetaSizeLimit = uint32(256 << 10) const blockSizeHardLimit = uint32(8 << (10 * 2)) func EncodeB64(bs []byte) string { - return enc.B64Encode(bs) + return base64.Encode(bs) } func DecodeB64(sb string) []byte { - buf, _ := enc.B64Decode(sb) + buf, _ := base64.Decode(sb) return buf } func EncodeB58(bs []byte) string { - return enc.B58Encode(bs) + return base58.Encode(bs) } func DecodeB58(sb string) []byte { - buf, _ := enc.B58Decode(sb) + buf, _ := base58.Decode(sb) return buf } diff --git a/types/genesis.go b/types/genesis.go index aadf0ac9a..2d6853e44 100644 --- a/types/genesis.go +++ b/types/genesis.go @@ -10,7 +10,8 @@ import ( "strings" "time" - "github.com/aergoio/aergo/v2/internal/enc" + "github.com/aergoio/aergo/v2/internal/enc/gob" + "github.com/aergoio/aergo/v2/internal/enc/hex" ) const ( @@ -280,7 +281,7 @@ func (g *Genesis) ChainID() ([]byte, error) { func (g Genesis) Bytes() []byte { // Omit the Balance to reduce the resulting data size. g.Balance = nil - if b, err := enc.GobEncode(g); err == nil { + if b, err := gob.Encode(g); err == nil { return b } return nil @@ -332,7 +333,7 @@ func GetDefaultGenesis() *Genesis { } func GetMainNetGenesis() *Genesis { - if bs, err := enc.HexDecode(MainNetGenesis); err == nil { + if bs, err := hex.Decode(MainNetGenesis); err == nil { var g Genesis if err := json.Unmarshal(bs, &g); err == nil { return &g @@ -341,7 +342,7 @@ func GetMainNetGenesis() *Genesis { return nil } func GetTestNetGenesis() *Genesis { - if bs, err := enc.HexDecode(TestNetGenesis); err == nil { + if bs, err := hex.Decode(TestNetGenesis); err == nil { var g Genesis if err := json.Unmarshal(bs, &g); err == nil { return &g @@ -372,7 +373,7 @@ func GetTestGenesis() *Genesis { // GetGenesisFromBytes decodes & return Genesis from b. func GetGenesisFromBytes(b []byte) *Genesis { g := &Genesis{} - if err := enc.GobDecode(b, g); err == nil { + if err := gob.Decode(b, g); err == nil { return g } return nil diff --git a/types/genesis_test.go b/types/genesis_test.go index 0da7cba65..9a4cedae4 100644 --- a/types/genesis_test.go +++ b/types/genesis_test.go @@ -7,7 +7,7 @@ import ( "testing" "time" - "github.com/aergoio/aergo/v2/internal/enc" + "github.com/aergoio/aergo/v2/internal/enc/base58" "github.com/davecgh/go-spew/spew" "github.com/stretchr/testify/assert" ) @@ -36,7 +36,7 @@ func TestGenesisChainID(t *testing.T) { a.Nil(err) a.True(g.ID.Equals(&defaultChainID)) fmt.Println("len:", len(chainID)) - fmt.Println("chain_id: ", enc.B58Encode(chainID)) + fmt.Println("chain_id: ", base58.Encode(chainID)) } func TestGenesisBytes(t *testing.T) { diff --git a/types/logging.go b/types/logging.go index 91154797c..a0a479876 100644 --- a/types/logging.go +++ b/types/logging.go @@ -8,7 +8,7 @@ package types import ( "fmt" - "github.com/aergoio/aergo/v2/internal/enc" + "github.com/aergoio/aergo/v2/internal/enc/base58" "github.com/rs/zerolog" ) @@ -17,7 +17,7 @@ type LogTxHash struct { } func (t LogTxHash) MarshalZerologObject(e *zerolog.Event) { - e.Str("txID", enc.B58Encode(t.Hash)) + e.Str("txID", base58.Encode(t.Hash)) } type LogTx struct { @@ -25,7 +25,7 @@ type LogTx struct { } func (t LogTx) MarshalZerologObject(e *zerolog.Event) { - e.Str("txID", enc.B58Encode(t.GetHash())).Str("account", enc.B58Encode(t.Body.Account)).Uint64("nonce", t.Body.Nonce) + e.Str("txID", base58.Encode(t.GetHash())).Str("account", base58.Encode(t.Body.Account)).Uint64("nonce", t.Body.Nonce) } type LogTrsactions struct { @@ -64,7 +64,7 @@ func marshalTrx(tr Transaction, a *zerolog.Array) { type LogBase58 []byte func (t LogBase58) String() string { - return enc.B58Encode(t) + return base58.Encode(t) } // LogAddr is thin wrapper which show base58 encoded form of wallet or smart contract diff --git a/types/logging_test.go b/types/logging_test.go index f21ccbef2..88383416d 100644 --- a/types/logging_test.go +++ b/types/logging_test.go @@ -4,7 +4,7 @@ import ( "testing" "github.com/aergoio/aergo-lib/log" - "github.com/aergoio/aergo/v2/internal/enc" + "github.com/aergoio/aergo/v2/internal/enc/base58" "github.com/rs/zerolog" ) @@ -70,7 +70,7 @@ func BenchmarkLogMemAllocationRunD(b *testing.B) { type LogB58Wrapper []byte func (t LogB58Wrapper) MarshalZerologObject(e *zerolog.Event) { - e.Str("b58", enc.B58Encode(t)) + e.Str("b58", base58.Encode(t)) } func BenchmarkLogMemAllocationWrapper(b *testing.B) { diff --git a/types/p2p_test.go b/types/p2p_test.go index 4683e102e..fd3747f69 100644 --- a/types/p2p_test.go +++ b/types/p2p_test.go @@ -9,14 +9,15 @@ import ( "fmt" "testing" - "github.com/aergoio/aergo/v2/internal/enc" + "github.com/aergoio/aergo/v2/internal/enc/base58" + "github.com/aergoio/aergo/v2/internal/enc/hex" "github.com/golang/protobuf/proto" "github.com/stretchr/testify/assert" ) func TestUnmarshalSize(t *testing.T) { - var dummyTxHash, _ = enc.B58Decode("4H4zAkAyRV253K5SNBJtBxqUgHEbZcXbWFFc6cmQHY45") - fmt.Println("Hash: ", enc.HexEncode(dummyTxHash)) + var dummyTxHash, _ = base58.Decode("4H4zAkAyRV253K5SNBJtBxqUgHEbZcXbWFFc6cmQHY45") + fmt.Println("Hash: ", hex.Encode(dummyTxHash)) sample := &NewTransactionsNotice{} @@ -34,7 +35,7 @@ func TestUnmarshalSize(t *testing.T) { actual, err = proto.Marshal(sample) assert.Nil(t, err) fmt.Println("Single hash notice size ", len(actual)) - fmt.Println("Hex: ", enc.HexEncode(actual)) + fmt.Println("Hex: ", hex.Encode(actual)) assert.Equal(t, expectedLen, len(actual)) // 100 hashes @@ -47,7 +48,7 @@ func TestUnmarshalSize(t *testing.T) { actual, err = proto.Marshal(sample) assert.Nil(t, err) fmt.Println("Hundred hashes notice size ", len(actual)) - fmt.Println("Hex: ", enc.HexEncode(actual[0:40])) + fmt.Println("Hex: ", hex.Encode(actual[0:40])) assert.Equal(t, expectedLen, len(actual)) // 1000 hashes @@ -60,7 +61,7 @@ func TestUnmarshalSize(t *testing.T) { actual, err = proto.Marshal(sample) assert.Nil(t, err) fmt.Println("Thousand hashes notice size ", len(actual)) - fmt.Println("Hex: ", enc.HexEncode(actual[0:40])) + fmt.Println("Hex: ", hex.Encode(actual[0:40])) assert.Equal(t, expectedLen, len(actual)) } diff --git a/types/p2plogging.go b/types/p2plogging.go index c4364a44a..1a366ed89 100644 --- a/types/p2plogging.go +++ b/types/p2plogging.go @@ -8,7 +8,7 @@ package types import ( "fmt" - "github.com/aergoio/aergo/v2/internal/enc" + "github.com/aergoio/aergo/v2/internal/enc/base58" "github.com/rs/zerolog" ) @@ -34,12 +34,12 @@ func (m LogB58EncMarshaller) MarshalZerologArray(a *zerolog.Array) { size := len(m.arr) if size > m.limit { for i := 0; i < m.limit-1; i++ { - a.Str(enc.B58Encode(m.arr[i])) + a.Str(base58.Encode(m.arr[i])) } a.Str(fmt.Sprintf("(and %d more)", size-m.limit+1)) } else { for _, element := range m.arr { - a.Str(enc.B58Encode(element)) + a.Str(base58.Encode(element)) } } } @@ -53,12 +53,12 @@ func (m LogBlockHashMarshaller) MarshalZerologArray(a *zerolog.Array) { size := len(m.arr) if size > m.limit { for i := 0; i < m.limit-1; i++ { - a.Str(enc.B58Encode(m.arr[i].GetHash())) + a.Str(base58.Encode(m.arr[i].GetHash())) } a.Str(fmt.Sprintf("(and %d more)", size-m.limit+1)) } else { for _, element := range m.arr { - a.Str(enc.B58Encode(element.GetHash())) + a.Str(base58.Encode(element.GetHash())) } } } @@ -134,15 +134,15 @@ func (m *NewTransactionsNotice) MarshalZerologObject(e *zerolog.Event) { } func (m *BlockProducedNotice) MarshalZerologObject(e *zerolog.Event) { - e.Str("bp", enc.B58Encode(m.ProducerID)).Uint64(LogBlkNo, m.BlockNo).Str(LogBlkHash, enc.B58Encode(m.Block.Hash)) + e.Str("bp", base58.Encode(m.ProducerID)).Uint64(LogBlkNo, m.BlockNo).Str(LogBlkHash, base58.Encode(m.Block.Hash)) } func (m *Ping) MarshalZerologObject(e *zerolog.Event) { - e.Str(LogBlkHash, enc.B58Encode(m.BestBlockHash)).Uint64(LogBlkNo, m.BestHeight) + e.Str(LogBlkHash, base58.Encode(m.BestBlockHash)).Uint64(LogBlkNo, m.BestHeight) } func (m *GetHashesRequest) MarshalZerologObject(e *zerolog.Event) { - e.Str("prev_hash", enc.B58Encode(m.PrevHash)).Uint64("prev_no", m.PrevNumber) + e.Str("prev_hash", base58.Encode(m.PrevHash)).Uint64("prev_no", m.PrevNumber) } func (m *GetHashesResponse) MarshalZerologObject(e *zerolog.Event) { @@ -150,7 +150,7 @@ func (m *GetHashesResponse) MarshalZerologObject(e *zerolog.Event) { } func (m *GetBlockHeadersRequest) MarshalZerologObject(e *zerolog.Event) { - e.Str(LogBlkHash, enc.B58Encode(m.Hash)).Uint64(LogBlkNo, m.Height).Bool("ascending", m.Asc).Uint32("size", m.Size) + e.Str(LogBlkHash, base58.Encode(m.Hash)).Uint64(LogBlkNo, m.Height).Bool("ascending", m.Asc).Uint32("size", m.Size) } func (m *GetBlockHeadersResponse) MarshalZerologObject(e *zerolog.Event) { @@ -162,7 +162,7 @@ func (m *GetHashByNo) MarshalZerologObject(e *zerolog.Event) { } func (m *GetHashByNoResponse) MarshalZerologObject(e *zerolog.Event) { - e.Str(LogRespStatus, m.Status.String()).Str(LogBlkHash, enc.B58Encode(m.BlockHash)) + e.Str(LogRespStatus, m.Status.String()).Str(LogBlkHash, base58.Encode(m.BlockHash)) } func (m *GetAncestorRequest) MarshalZerologObject(e *zerolog.Event) { @@ -170,15 +170,15 @@ func (m *GetAncestorRequest) MarshalZerologObject(e *zerolog.Event) { } func (m *GetAncestorResponse) MarshalZerologObject(e *zerolog.Event) { - e.Str(LogRespStatus, m.Status.String()).Str(LogBlkHash, enc.B58Encode(m.AncestorHash)).Uint64(LogBlkNo, m.AncestorNo) + e.Str(LogRespStatus, m.Status.String()).Str(LogBlkHash, base58.Encode(m.AncestorHash)).Uint64(LogBlkNo, m.AncestorNo) } func (m *GetClusterInfoRequest) MarshalZerologObject(e *zerolog.Event) { - e.Str("best_hash", enc.B58Encode(m.BestBlockHash)) + e.Str("best_hash", base58.Encode(m.BestBlockHash)) } func (m *GetClusterInfoResponse) MarshalZerologObject(e *zerolog.Event) { - e.Str(LogChainID, enc.B58Encode(m.ChainID)).Str("err", m.Error).Array("members", RaftMbrsMarshaller{arr: m.MbrAttrs, limit: 10}).Uint64("cluster_id", m.ClusterID) + e.Str(LogChainID, base58.Encode(m.ChainID)).Str("err", m.Error).Array("members", RaftMbrsMarshaller{arr: m.MbrAttrs, limit: 10}).Uint64("cluster_id", m.ClusterID) } func (m *IssueCertificateResponse) MarshalZerologObject(e *zerolog.Event) { diff --git a/types/receipt.go b/types/receipt.go index 4155e2928..a4757b22b 100644 --- a/types/receipt.go +++ b/types/receipt.go @@ -10,7 +10,7 @@ import ( "reflect" "strconv" - "github.com/aergoio/aergo/v2/internal/enc" + "github.com/aergoio/aergo/v2/internal/enc/base58" "github.com/aergoio/aergo/v2/internal/merkle" "github.com/golang/protobuf/jsonpb" "github.com/minio/sha256-simd" @@ -352,7 +352,7 @@ func (r *Receipt) MarshalJSON() ([]byte, error) { b.WriteString(`{"BlockNo":`) b.WriteString(fmt.Sprintf("%d", r.BlockNo)) b.WriteString(`,"BlockHash":"`) - b.WriteString(enc.B58Encode(r.BlockHash)) + b.WriteString(base58.Encode(r.BlockHash)) b.WriteString(`","contractAddress":"`) b.WriteString(EncodeAddress(r.ContractAddress)) b.WriteString(`","status":"`) @@ -368,7 +368,7 @@ func (r *Receipt) MarshalJSON() ([]byte, error) { b.WriteString(r.Ret) } b.WriteString(`,"txHash":"`) - b.WriteString(enc.B58Encode(r.TxHash)) + b.WriteString(base58.Encode(r.TxHash)) b.WriteString(`","txIndex":`) b.WriteString(fmt.Sprintf("%d", r.TxIndex)) b.WriteString(`,"from":"`) @@ -731,11 +731,11 @@ func (ev *Event) MarshalJSON() ([]byte, error) { b.WriteString(`","Args":`) b.WriteString(ev.JsonArgs) b.WriteString(`,"txHash":"`) - b.WriteString(enc.B58Encode(ev.TxHash)) + b.WriteString(base58.Encode(ev.TxHash)) b.WriteString(`","EventIdx":`) b.WriteString(fmt.Sprintf("%d", ev.EventIdx)) b.WriteString(`,"BlockHash":"`) - b.WriteString(enc.B58Encode(ev.BlockHash)) + b.WriteString(base58.Encode(ev.BlockHash)) b.WriteString(`","BlockNo":`) b.WriteString(fmt.Sprintf("%d", ev.BlockNo)) b.WriteString(`,"TxIndex":`) diff --git a/types/state.go b/types/state.go index 5ee622ed8..d0cbe63ac 100644 --- a/types/state.go +++ b/types/state.go @@ -7,7 +7,7 @@ import ( "reflect" "github.com/aergoio/aergo/v2/internal/common" - "github.com/aergoio/aergo/v2/internal/enc" + "github.com/aergoio/aergo/v2/internal/enc/base58" ) const ( @@ -58,7 +58,7 @@ func ToHashID(hash []byte) HashID { return HashID(buf) } func (id HashID) String() string { - return enc.B58Encode(id[:]) + return base58.Encode(id[:]) } // Bytes make a byte slice from id diff --git a/types/transaction.go b/types/transaction.go index cc81c1104..17cbeb80c 100644 --- a/types/transaction.go +++ b/types/transaction.go @@ -8,7 +8,7 @@ import ( "strings" "github.com/aergoio/aergo/v2/fee" - "github.com/aergoio/aergo/v2/internal/enc" + "github.com/aergoio/aergo/v2/internal/enc/base58" "github.com/golang/protobuf/proto" ) @@ -203,7 +203,7 @@ func ValidateSystemTx(tx *TxBody) error { return ErrTxInvalidPayload } unique[encoded]++ - candidate, err := enc.B58Decode(encoded) + candidate, err := base58.Decode(encoded) if err != nil { return ErrTxInvalidPayload } From 04c5a261bf378913b7abdd82dbfb0d1fccb5aaae Mon Sep 17 00:00:00 2001 From: kch Date: Mon, 6 Nov 2023 03:46:09 +0000 Subject: [PATCH 6/6] move proto encode to internal --- chain/chaindb.go | 8 +++---- chain/chaindbForRaft.go | 14 ++++++------- chain/chainhandle.go | 2 +- cmd/aergocli/util/grpccommon.go | 4 ++-- cmd/colaris/cmd/common.go | 2 +- consensus/chain/tx.go | 2 +- consensus/impl/raftv2/raftserver.go | 6 +++--- internal/enc/proto/proto.go | 29 ++++++++++++++++++++++++++ mempool/mempool.go | 6 +++--- p2p/p2pcommon/message.go | 2 +- p2p/p2putil/certificate_test.go | 2 +- p2p/p2putil/protobuf.go | 8 +++---- p2p/p2putil/protobuf_test.go | 8 +++---- p2p/raftsupport/clusterreceiver.go | 2 +- p2p/raftsupport/concclusterreceiver.go | 2 +- p2p/raftsupport/snapshotreceiver.go | 4 ++-- p2p/raftsupport/snapshotsender.go | 4 ++-- p2p/remotepeer_test.go | 2 +- p2p/signature.go | 6 +++--- p2p/subproto/addrs_test.go | 2 +- p2p/subproto/bp_test.go | 2 +- p2p/subproto/getblock.go | 2 +- p2p/synctx.go | 2 +- p2p/v030/v030io_test.go | 14 ++++++------- polaris/server/mapservice_test.go | 2 +- state/contract.go | 4 ++-- state/statebuffer.go | 4 ++-- state/statedata.go | 6 +++--- tools/mpdumpdiag/main.go | 6 +++--- types/blockchain.go | 2 +- types/blockchain_test.go | 2 +- types/p2p_test.go | 10 ++++----- types/transaction.go | 2 +- 33 files changed, 101 insertions(+), 72 deletions(-) create mode 100644 internal/enc/proto/proto.go diff --git a/chain/chaindb.go b/chain/chaindb.go index 658a6a121..52b50495c 100644 --- a/chain/chaindb.go +++ b/chain/chaindb.go @@ -18,9 +18,9 @@ import ( "github.com/aergoio/aergo/v2/internal/common" "github.com/aergoio/aergo/v2/internal/enc/base58" "github.com/aergoio/aergo/v2/internal/enc/gob" + "github.com/aergoio/aergo/v2/internal/enc/proto" "github.com/aergoio/aergo/v2/types" "github.com/aergoio/aergo/v2/types/dbkey" - "github.com/golang/protobuf/proto" ) var ( @@ -274,7 +274,7 @@ func (cdb *ChainDB) loadData(key []byte, pb proto.Message) error { return fmt.Errorf("failed to load data: key=%v", key) } //logger.Debugf(" loadData: key=%d, len=%d, val=%s\n", Btoi(key), len(buf), enc.ToString(buf)) - err := proto.Unmarshal(buf, pb) + err := proto.Decode(buf, pb) if err != nil { return fmt.Errorf("failed to unmarshal: key=%v, len=%d", key, len(buf)) } @@ -461,7 +461,7 @@ func (cdb *ChainDB) addTx(dbtx *db.Transaction, tx *types.Tx, blockHash []byte, BlockHash: blockHash, Idx: int32(idx), } - txidxbytes, err := proto.Marshal(&txidx) + txidxbytes, err := proto.Encode(&txidx) if err != nil { return err } @@ -486,7 +486,7 @@ func (cdb *ChainDB) addBlock(dbtx db.Transaction, block *types.Block) error { // assumption: not an orphan // fork can be here logger.Debug().Uint64("blockNo", blockNo).Msg("add block to db") - blockBytes, err := proto.Marshal(block) + blockBytes, err := proto.Encode(block) if err != nil { logger.Error().Err(err).Uint64("no", blockNo).Str("hash", block.ID()).Msg("failed to add block") return err diff --git a/chain/chaindbForRaft.go b/chain/chaindbForRaft.go index 14a754d54..5f18f18ed 100644 --- a/chain/chaindbForRaft.go +++ b/chain/chaindbForRaft.go @@ -6,10 +6,10 @@ import ( "github.com/aergoio/aergo-lib/db" "github.com/aergoio/aergo/v2/consensus" "github.com/aergoio/aergo/v2/internal/enc/gob" + "github.com/aergoio/aergo/v2/internal/enc/proto" "github.com/aergoio/aergo/v2/types" "github.com/aergoio/aergo/v2/types/dbkey" "github.com/aergoio/etcd/raft/raftpb" - "github.com/golang/protobuf/proto" ) var ( @@ -126,7 +126,7 @@ func (cdb *ChainDB) WriteHardState(hardstate *raftpb.HardState) error { logger.Info().Uint64("term", hardstate.Term).Str("vote", types.Uint64ToHexaString(hardstate.Vote)).Uint64("commit", hardstate.Commit).Msg("save hard state") - if data, err = proto.Marshal(hardstate); err != nil { + if data, err = proto.Encode(hardstate); err != nil { logger.Panic().Msg("failed to marshal raft state") } dbTx.Set(dbkey.RaftState(), data) @@ -143,7 +143,7 @@ func (cdb *ChainDB) GetHardState() (*raftpb.HardState, error) { } state := &raftpb.HardState{} - if err := proto.Unmarshal(data, state); err != nil { + if err := proto.Decode(data, state); err != nil { logger.Panic().Msg("failed to unmarshal raft state") } @@ -354,7 +354,7 @@ func (cdb *ChainDB) WriteSnapshot(snap *raftpb.Snapshot) error { } logger.Debug().Str("snapshot", consensus.SnapToString(snap, &snapdata)).Msg("write snapshot to wal") - data, err := proto.Marshal(snap) + data, err := proto.Encode(snap) if err != nil { return err } @@ -402,7 +402,7 @@ func (cdb *ChainDB) GetSnapshot() (*raftpb.Snapshot, error) { } snap := &raftpb.Snapshot{} - if err := proto.Unmarshal(data, snap); err != nil { + if err := proto.Decode(data, snap); err != nil { logger.Panic().Msg("failed to unmarshal raft snap") return nil, ErrInvalidRaftSnapshot } @@ -471,7 +471,7 @@ func (cdb *ChainDB) writeConfChangeProgress(dbTx db.Transaction, id uint64, prog var data []byte var err error - if data, err = proto.Marshal(progress); err != nil { + if data, err = proto.Encode(progress); err != nil { logger.Error().Msg("failed to marshal confChangeProgress") return err } @@ -489,7 +489,7 @@ func (cdb *ChainDB) GetConfChangeProgress(id uint64) (*types.ConfChangeProgress, var progress types.ConfChangeProgress - if err := proto.Unmarshal(data, &progress); err != nil { + if err := proto.Decode(data, &progress); err != nil { logger.Error().Msg("failed to unmarshal raft state") return nil, ErrInvalidCCProgress } diff --git a/chain/chainhandle.go b/chain/chainhandle.go index 12a8abd32..be972b577 100644 --- a/chain/chainhandle.go +++ b/chain/chainhandle.go @@ -19,10 +19,10 @@ import ( "github.com/aergoio/aergo/v2/contract/name" "github.com/aergoio/aergo/v2/contract/system" "github.com/aergoio/aergo/v2/internal/enc/base58" + "github.com/aergoio/aergo/v2/internal/enc/proto" "github.com/aergoio/aergo/v2/message" "github.com/aergoio/aergo/v2/state" "github.com/aergoio/aergo/v2/types" - "github.com/golang/protobuf/proto" ) var ( diff --git a/cmd/aergocli/util/grpccommon.go b/cmd/aergocli/util/grpccommon.go index e21af7fba..11a6b3b93 100644 --- a/cmd/aergocli/util/grpccommon.go +++ b/cmd/aergocli/util/grpccommon.go @@ -9,8 +9,8 @@ import ( "fmt" "github.com/aergoio/aergo/v2/cmd/aergocli/util/encoding/json" + "github.com/aergoio/aergo/v2/internal/enc/proto" "github.com/aergoio/aergo/v2/types" - protobuf "github.com/golang/protobuf/proto" "google.golang.org/grpc" ) @@ -44,7 +44,7 @@ func (c *ConnClient) Close() { } // JSON converts protobuf message(struct) to json notation -func JSON(pb protobuf.Message) string { +func JSON(pb proto.Message) string { jsonout, err := json.MarshalIndent(pb, "", " ") if err != nil { fmt.Printf("Failed: %s\n", err.Error()) diff --git a/cmd/colaris/cmd/common.go b/cmd/colaris/cmd/common.go index 848e30338..a443872ea 100644 --- a/cmd/colaris/cmd/common.go +++ b/cmd/colaris/cmd/common.go @@ -9,8 +9,8 @@ import ( "fmt" "github.com/aergoio/aergo/v2/cmd/aergocli/util/encoding/json" + "github.com/aergoio/aergo/v2/internal/enc/proto" "github.com/aergoio/aergo/v2/types" - "github.com/golang/protobuf/proto" "google.golang.org/grpc" ) diff --git a/consensus/chain/tx.go b/consensus/chain/tx.go index 9d8412c68..a9af96d20 100644 --- a/consensus/chain/tx.go +++ b/consensus/chain/tx.go @@ -13,11 +13,11 @@ import ( "github.com/aergoio/aergo-lib/log" "github.com/aergoio/aergo/v2/chain" "github.com/aergoio/aergo/v2/contract" + "github.com/aergoio/aergo/v2/internal/enc/proto" "github.com/aergoio/aergo/v2/message" "github.com/aergoio/aergo/v2/pkg/component" "github.com/aergoio/aergo/v2/state" "github.com/aergoio/aergo/v2/types" - "github.com/golang/protobuf/proto" ) var ( diff --git a/consensus/impl/raftv2/raftserver.go b/consensus/impl/raftv2/raftserver.go index 33307fa20..f514d6465 100644 --- a/consensus/impl/raftv2/raftserver.go +++ b/consensus/impl/raftv2/raftserver.go @@ -30,6 +30,7 @@ import ( "github.com/aergoio/aergo/v2/chain" "github.com/aergoio/aergo/v2/consensus" + "github.com/aergoio/aergo/v2/internal/enc/proto" "github.com/aergoio/aergo/v2/message" "github.com/aergoio/aergo/v2/p2p/p2pcommon" "github.com/aergoio/aergo/v2/pkg/component" @@ -40,7 +41,6 @@ import ( "github.com/aergoio/etcd/raft/raftpb" "github.com/aergoio/etcd/rafthttp" "github.com/aergoio/etcd/snap" - "github.com/golang/protobuf/proto" ) const ( @@ -1527,7 +1527,7 @@ func (rs *raftServer) GetExistingCluster() (*Cluster, *types.HardStateInfo, erro func marshalEntryData(block *types.Block) ([]byte, error) { var data []byte var err error - if data, err = proto.Marshal(block); err != nil { + if data, err = proto.Encode(block); err != nil { logger.Fatal().Err(err).Msg("poposed data is invalid") } @@ -1540,7 +1540,7 @@ var ( func unmarshalEntryData(data []byte) (*types.Block, error) { block := &types.Block{} - if err := proto.Unmarshal(data, block); err != nil { + if err := proto.Decode(data, block); err != nil { return block, ErrUnmarshal } diff --git a/internal/enc/proto/proto.go b/internal/enc/proto/proto.go new file mode 100644 index 000000000..c8d41984f --- /dev/null +++ b/internal/enc/proto/proto.go @@ -0,0 +1,29 @@ +package proto + +import ( + "github.com/golang/protobuf/proto" +) + +type Message = proto.Message + +// Encode encodes e by using gob and returns. +func Encode(m proto.Message) ([]byte, error) { + return proto.Marshal(m) +} + +// Decode decodes a gob-encoded value v. +func Decode(v []byte, m proto.Message) error { + return proto.Unmarshal(v, m) +} + +func Size(m proto.Message) int { + return proto.Size(m) +} + +func Equal(m1, m2 proto.Message) bool { + return proto.Equal(m1, m2) +} + +func Clone(m proto.Message) proto.Message { + return proto.Clone(m) +} diff --git a/mempool/mempool.go b/mempool/mempool.go index 7c9ae89fa..1599a6736 100644 --- a/mempool/mempool.go +++ b/mempool/mempool.go @@ -29,11 +29,11 @@ import ( "github.com/aergoio/aergo/v2/fee" "github.com/aergoio/aergo/v2/internal/common" "github.com/aergoio/aergo/v2/internal/enc/base58" + "github.com/aergoio/aergo/v2/internal/enc/proto" "github.com/aergoio/aergo/v2/message" "github.com/aergoio/aergo/v2/pkg/component" "github.com/aergoio/aergo/v2/state" "github.com/aergoio/aergo/v2/types" - "github.com/golang/protobuf/proto" ) const ( @@ -873,7 +873,7 @@ func (mp *MemPool) loadTxs() { break } - err = proto.Unmarshal(buffer, &buf) + err = proto.Decode(buffer, &buf) if err != nil { mp.Error().Err(err).Msg("errr on unmarshalling tx during loading") continue @@ -916,7 +916,7 @@ Dump: var total_data []byte start := time.Now() - data, err := proto.Marshal(v.GetTx()) + data, err := proto.Encode(v.GetTx()) if err != nil { mp.Error().Err(err).Msg("Marshal failed") continue diff --git a/p2p/p2pcommon/message.go b/p2p/p2pcommon/message.go index 5fb0c6e42..9904ee383 100644 --- a/p2p/p2pcommon/message.go +++ b/p2p/p2pcommon/message.go @@ -9,8 +9,8 @@ package p2pcommon import ( "time" + "github.com/aergoio/aergo/v2/internal/enc/proto" "github.com/aergoio/aergo/v2/types" - "github.com/golang/protobuf/proto" ) // Message is unit structure transferred from a peer to another peer. diff --git a/p2p/p2putil/certificate_test.go b/p2p/p2putil/certificate_test.go index a41d726c2..edfb2701c 100644 --- a/p2p/p2putil/certificate_test.go +++ b/p2p/p2putil/certificate_test.go @@ -7,10 +7,10 @@ import ( "time" "github.com/aergoio/aergo/v2/internal/enc/base58" + "github.com/aergoio/aergo/v2/internal/enc/proto" "github.com/aergoio/aergo/v2/p2p/p2pcommon" "github.com/aergoio/aergo/v2/types" "github.com/btcsuite/btcd/btcec" - "github.com/golang/protobuf/proto" ) func TestNewAgentCertV1(t *testing.T) { diff --git a/p2p/p2putil/protobuf.go b/p2p/p2putil/protobuf.go index 8faf2953a..9a11334bd 100644 --- a/p2p/p2putil/protobuf.go +++ b/p2p/p2putil/protobuf.go @@ -6,8 +6,8 @@ package p2putil import ( + "github.com/aergoio/aergo/v2/internal/enc/proto" "github.com/aergoio/aergo/v2/p2p/p2pcommon" - "github.com/golang/protobuf/proto" ) func CalculateFieldDescSize(varSize int) int { @@ -30,13 +30,13 @@ func CalculateFieldDescSize(varSize int) int { } func MarshalMessageBody(message p2pcommon.MessageBody) ([]byte, error) { - return proto.Marshal(message) + return proto.Encode(message) } func UnmarshalMessageBody(data []byte, msgData p2pcommon.MessageBody) error { - return proto.Unmarshal(data, msgData) + return proto.Decode(data, msgData) } func UnmarshalAndReturn(data []byte, msgData p2pcommon.MessageBody) (p2pcommon.MessageBody, error) { - return msgData, proto.Unmarshal(data, msgData) + return msgData, proto.Decode(data, msgData) } diff --git a/p2p/p2putil/protobuf_test.go b/p2p/p2putil/protobuf_test.go index be7837396..2e918e44a 100644 --- a/p2p/p2putil/protobuf_test.go +++ b/p2p/p2putil/protobuf_test.go @@ -10,8 +10,8 @@ import ( "testing" "github.com/aergoio/aergo/v2/internal/enc/base58" + "github.com/aergoio/aergo/v2/internal/enc/proto" "github.com/aergoio/aergo/v2/types" - "github.com/golang/protobuf/proto" "github.com/stretchr/testify/assert" ) @@ -19,10 +19,10 @@ var dummyTxHash, _ = base58.Decode("4H4zAkAyRV253K5SNBJtBxqUgHEbZcXbWFFc6cmQHY45 func Test_MarshalTxResp(t *testing.T) { dummyTx := &types.Tx{Hash: dummyTxHash, Body: &types.TxBody{Payload: []byte("It's a good day to die.")}} - txMarshaled, _ := proto.Marshal(dummyTx) + txMarshaled, _ := proto.Encode(dummyTx) txSize := len(dummyTxHash) + 2 + len(txMarshaled) + 2 // hash+ field desc of hash + tx+field desc of tx //fmt.Println("TX : ",hex.HexEncode(txMarshaled)) - emptyMarshaled, _ := proto.Marshal(&types.GetTransactionsResponse{}) + emptyMarshaled, _ := proto.Encode(&types.GetTransactionsResponse{}) emptySize := len(emptyMarshaled) //fmt.Println("EMPTY: ",hex.HexEncode(emptyMarshaled)) //fmt.Printf("Size of All nil: %d , tx size: %d ",emptySize, txSize) @@ -50,7 +50,7 @@ func Test_MarshalTxResp(t *testing.T) { txSlice = append(txSlice, dummyTx) } sampleRsp := &types.GetTransactionsResponse{Hashes: hashSlice, Txs: txSlice} - actual, err := proto.Marshal(sampleRsp) + actual, err := proto.Encode(sampleRsp) if err != nil { t.Errorf("Invalid proto error %s", err.Error()) } diff --git a/p2p/raftsupport/clusterreceiver.go b/p2p/raftsupport/clusterreceiver.go index a4872a7cd..12af9e1cc 100644 --- a/p2p/raftsupport/clusterreceiver.go +++ b/p2p/raftsupport/clusterreceiver.go @@ -10,10 +10,10 @@ import ( "sync" "time" + "github.com/aergoio/aergo/v2/internal/enc/proto" "github.com/aergoio/aergo/v2/message" "github.com/aergoio/aergo/v2/p2p/p2pcommon" "github.com/aergoio/aergo/v2/types" - "github.com/golang/protobuf/proto" "github.com/pkg/errors" ) diff --git a/p2p/raftsupport/concclusterreceiver.go b/p2p/raftsupport/concclusterreceiver.go index aaee3b0c1..0ff67c134 100644 --- a/p2p/raftsupport/concclusterreceiver.go +++ b/p2p/raftsupport/concclusterreceiver.go @@ -11,11 +11,11 @@ import ( "time" "github.com/aergoio/aergo-lib/log" + "github.com/aergoio/aergo/v2/internal/enc/proto" "github.com/aergoio/aergo/v2/message" "github.com/aergoio/aergo/v2/p2p/p2pcommon" "github.com/aergoio/aergo/v2/p2p/p2putil" "github.com/aergoio/aergo/v2/types" - "github.com/golang/protobuf/proto" "github.com/pkg/errors" ) diff --git a/p2p/raftsupport/snapshotreceiver.go b/p2p/raftsupport/snapshotreceiver.go index 8d2cd4df4..2a46ff7d2 100644 --- a/p2p/raftsupport/snapshotreceiver.go +++ b/p2p/raftsupport/snapshotreceiver.go @@ -12,12 +12,12 @@ import ( "github.com/aergoio/aergo-lib/log" "github.com/aergoio/aergo/v2/consensus" + "github.com/aergoio/aergo/v2/internal/enc/proto" "github.com/aergoio/aergo/v2/p2p/p2pcommon" "github.com/aergoio/aergo/v2/p2p/p2putil" "github.com/aergoio/aergo/v2/types" rtypes "github.com/aergoio/etcd/pkg/types" "github.com/aergoio/etcd/raft/raftpb" - "github.com/golang/protobuf/proto" ) const ( @@ -106,7 +106,7 @@ func (s *snapshotReceiver) Receive() { } func (s *snapshotReceiver) sendResp(w io.Writer, resp *types.SnapshotResponse) { - b, err := proto.Marshal(resp) + b, err := proto.Encode(resp) if err == nil { bytebuf := make([]byte, SnapRespHeaderLength) binary.BigEndian.PutUint32(bytebuf, uint32(len(b))) diff --git a/p2p/raftsupport/snapshotsender.go b/p2p/raftsupport/snapshotsender.go index 125a1d14f..327df5b36 100644 --- a/p2p/raftsupport/snapshotsender.go +++ b/p2p/raftsupport/snapshotsender.go @@ -15,6 +15,7 @@ import ( "github.com/aergoio/aergo-lib/log" "github.com/aergoio/aergo/v2/consensus" + "github.com/aergoio/aergo/v2/internal/enc/proto" "github.com/aergoio/aergo/v2/p2p/p2pcommon" "github.com/aergoio/aergo/v2/p2p/p2putil" "github.com/aergoio/aergo/v2/types" @@ -22,7 +23,6 @@ import ( "github.com/aergoio/etcd/raft" "github.com/aergoio/etcd/raft/raftpb" "github.com/aergoio/etcd/snap" - "github.com/golang/protobuf/proto" core "github.com/libp2p/go-libp2p-core" ) @@ -171,7 +171,7 @@ func readWireHSResp(rd io.Reader) (resp types.SnapshotResponse, err error) { return } - err = proto.Unmarshal(bodyBuf, &resp) + err = proto.Decode(bodyBuf, &resp) return } func (s *snapshotSender) createSnapBody(merged snap.Message) io.ReadCloser { diff --git a/p2p/remotepeer_test.go b/p2p/remotepeer_test.go index ade9dc57e..fb27467d1 100644 --- a/p2p/remotepeer_test.go +++ b/p2p/remotepeer_test.go @@ -232,7 +232,7 @@ func TestRemotePeer_handleMsg(t *testing.T) { msg.On("Subprotocol").Return(PingRequest) } bodyStub := &types.Ping{} - bytes, _ := proto.Marshal(bodyStub) + bytes, _ := proto.Encode(bodyStub) msg.On("ID").Return(sampleMsgID) msg.On("Payload").Return(bytes) mockMsgHandler.On("parsePayload", mock.AnythingOfType("[]uint8")).Return(bodyStub, tt.args.parerr) diff --git a/p2p/signature.go b/p2p/signature.go index e596828b6..722aa97ee 100644 --- a/p2p/signature.go +++ b/p2p/signature.go @@ -8,9 +8,9 @@ package p2p import ( "fmt" + "github.com/aergoio/aergo/v2/internal/enc/proto" "github.com/aergoio/aergo/v2/p2p/p2pcommon" "github.com/aergoio/aergo/v2/types" - "github.com/golang/protobuf/proto" "github.com/libp2p/go-libp2p-core/crypto" ) @@ -33,7 +33,7 @@ func newDefaultMsgSigner(privKey crypto.PrivKey, pubKey crypto.PubKey, peerID ty func (pm *defaultMsgSigner) SignMsg(message *types.P2PMessage) error { message.Header.PeerID = pm.pidBytes message.Header.NodePubKey = pm.pubKeyBytes - data, err := proto.Marshal(&types.P2PMessage{Header: canonicalizeHeader(message.Header), Data: message.Data}) + data, err := proto.Encode(&types.P2PMessage{Header: canonicalizeHeader(message.Header), Data: message.Data}) if err != nil { return err } @@ -82,7 +82,7 @@ func (pm *defaultMsgSigner) VerifyMsg(msg *types.P2PMessage, senderID types.Peer } } - data, _ := proto.Marshal(&types.P2PMessage{Header: canonicalizeHeader(msg.Header), Data: msg.Data}) + data, _ := proto.Encode(&types.P2PMessage{Header: canonicalizeHeader(msg.Header), Data: msg.Data}) return verifyBytes(data, signature, pubKey) } diff --git a/p2p/subproto/addrs_test.go b/p2p/subproto/addrs_test.go index 1d789caf6..c94622892 100644 --- a/p2p/subproto/addrs_test.go +++ b/p2p/subproto/addrs_test.go @@ -10,11 +10,11 @@ import ( "testing" "github.com/aergoio/aergo-lib/log" + "github.com/aergoio/aergo/v2/internal/enc/proto" "github.com/aergoio/aergo/v2/p2p/p2pcommon" "github.com/aergoio/aergo/v2/p2p/p2pmock" "github.com/aergoio/aergo/v2/types" "github.com/golang/mock/gomock" - "github.com/golang/protobuf/proto" ) var samplePeers []p2pcommon.RemotePeer diff --git a/p2p/subproto/bp_test.go b/p2p/subproto/bp_test.go index eb823eaab..a6411f0de 100644 --- a/p2p/subproto/bp_test.go +++ b/p2p/subproto/bp_test.go @@ -11,12 +11,12 @@ import ( "github.com/aergoio/aergo-lib/log" "github.com/aergoio/aergo/v2/internal/enc/base58" + "github.com/aergoio/aergo/v2/internal/enc/proto" "github.com/aergoio/aergo/v2/p2p/p2pcommon" "github.com/aergoio/aergo/v2/p2p/p2pmock" "github.com/aergoio/aergo/v2/p2p/p2putil" "github.com/aergoio/aergo/v2/types" "github.com/golang/mock/gomock" - "github.com/golang/protobuf/proto" "github.com/libp2p/go-libp2p-core/crypto" ) diff --git a/p2p/subproto/getblock.go b/p2p/subproto/getblock.go index a58742a1a..be3042131 100644 --- a/p2p/subproto/getblock.go +++ b/p2p/subproto/getblock.go @@ -10,10 +10,10 @@ import ( "github.com/aergoio/aergo-lib/log" "github.com/aergoio/aergo/v2/internal/enc/base58" + "github.com/aergoio/aergo/v2/internal/enc/proto" "github.com/aergoio/aergo/v2/p2p/p2pcommon" "github.com/aergoio/aergo/v2/p2p/p2putil" "github.com/aergoio/aergo/v2/types" - "github.com/golang/protobuf/proto" ) type blockRequestHandler struct { diff --git a/p2p/synctx.go b/p2p/synctx.go index a16878d86..6eeda2708 100644 --- a/p2p/synctx.go +++ b/p2p/synctx.go @@ -8,12 +8,12 @@ import ( "time" "github.com/aergoio/aergo-lib/log" + "github.com/aergoio/aergo/v2/internal/enc/proto" "github.com/aergoio/aergo/v2/message" "github.com/aergoio/aergo/v2/p2p/p2pcommon" "github.com/aergoio/aergo/v2/p2p/p2putil" "github.com/aergoio/aergo/v2/p2p/subproto" "github.com/aergoio/aergo/v2/types" - "github.com/golang/protobuf/proto" lru "github.com/hashicorp/golang-lru" ) diff --git a/p2p/v030/v030io_test.go b/p2p/v030/v030io_test.go index 25ff18d51..ca0f930c8 100644 --- a/p2p/v030/v030io_test.go +++ b/p2p/v030/v030io_test.go @@ -14,10 +14,10 @@ import ( "time" "github.com/aergoio/aergo/v2/internal/enc/base58" + "github.com/aergoio/aergo/v2/internal/enc/proto" "github.com/aergoio/aergo/v2/p2p/p2pcommon" "github.com/aergoio/aergo/v2/types" "github.com/gofrs/uuid" - "github.com/golang/protobuf/proto" "github.com/stretchr/testify/assert" ) @@ -86,7 +86,7 @@ func Test_ReadWrite(t *testing.T) { t.Run(test.name, func(t *testing.T) { sizeChecker, sizeChecker2 := ioSum{}, ioSum{} samplePData := &types.NewTransactionsNotice{TxHashes: test.ids} - payload, _ := proto.Marshal(samplePData) + payload, _ := proto.Encode(samplePData) sample := p2pcommon.NewMessageValue(p2pcommon.NewTxNotice, sampleID, p2pcommon.EmptyID, time.Now().UnixNano(), payload) buf := bytes.NewBuffer(nil) @@ -138,7 +138,7 @@ func TestV030Writer_WriteError(t *testing.T) { //sampleUUID, _ := uuid.NewRandom() //copy(sampleID[:], sampleUUID[:]) //samplePData := &types.NewTransactionsNotice{TxHashes:sampleTxs} - //payload, _ := proto.Marshal(samplePData) + //payload, _ := proto.Encode(samplePData) //sample := &MessageValue{subProtocol: subproto.NewTxNotice, id: sampleID, timestamp: time.Now().UnixNano(), length: uint32(len(payload)), payload: payload} //mockWriter := make(MockWriter) //mockWriter.On("Write", mock.Anything).Return(fmt.Errorf("writer error")) @@ -154,14 +154,14 @@ func BenchmarkV030Writer_WriteMsg(b *testing.B) { timestamp := time.Now().UnixNano() smallPData := &types.NewTransactionsNotice{} - payload, _ := proto.Marshal(smallPData) + payload, _ := proto.Encode(smallPData) smallMsg := p2pcommon.NewMessageValue(p2pcommon.NewTxNotice, sampleID, p2pcommon.EmptyID, timestamp, payload) bigHashes := make([][]byte, 0, len(sampleTxs)*10000) for i := 0; i < 10000; i++ { bigHashes = append(bigHashes, sampleTxs...) } bigPData := &types.NewTransactionsNotice{TxHashes: bigHashes} - payload, _ = proto.Marshal(bigPData) + payload, _ = proto.Encode(bigPData) bigMsg := p2pcommon.NewMessageValue(p2pcommon.NewTxNotice, sampleID, p2pcommon.EmptyID, timestamp, payload) benchmarks := []struct { @@ -198,7 +198,7 @@ func BenchmarkV030Reader_ReadMsg(b *testing.B) { timestamp := time.Now().UnixNano() smallPData := &types.NewTransactionsNotice{} - payload, _ := proto.Marshal(smallPData) + payload, _ := proto.Encode(smallPData) smallMsg := p2pcommon.NewMessageValue(p2pcommon.NewTxNotice, sampleID, p2pcommon.EmptyID, timestamp, payload) smallBytes := getMarshaledV030(smallMsg, 1) bigHashes := make([][]byte, 0, len(sampleTxs)*10000) @@ -206,7 +206,7 @@ func BenchmarkV030Reader_ReadMsg(b *testing.B) { bigHashes = append(bigHashes, sampleTxs...) } bigPData := &types.NewTransactionsNotice{TxHashes: bigHashes} - payload, _ = proto.Marshal(bigPData) + payload, _ = proto.Encode(bigPData) bigMsg := p2pcommon.NewMessageValue(p2pcommon.NewTxNotice, sampleID, p2pcommon.EmptyID, timestamp, payload) bigBytes := getMarshaledV030(bigMsg, 1) diff --git a/polaris/server/mapservice_test.go b/polaris/server/mapservice_test.go index 73e7151fd..a810e8670 100644 --- a/polaris/server/mapservice_test.go +++ b/polaris/server/mapservice_test.go @@ -14,6 +14,7 @@ import ( "time" "github.com/aergoio/aergo/v2/config" + "github.com/aergoio/aergo/v2/internal/enc/proto" "github.com/aergoio/aergo/v2/p2p/p2pcommon" "github.com/aergoio/aergo/v2/p2p/p2pmock" "github.com/aergoio/aergo/v2/p2p/p2putil" @@ -21,7 +22,6 @@ import ( "github.com/aergoio/aergo/v2/polaris/common" "github.com/aergoio/aergo/v2/types" "github.com/golang/mock/gomock" - "github.com/golang/protobuf/proto" "github.com/libp2p/go-libp2p-core/network" "github.com/stretchr/testify/assert" ) diff --git a/state/contract.go b/state/contract.go index a0b9a9998..df7511ea0 100644 --- a/state/contract.go +++ b/state/contract.go @@ -6,8 +6,8 @@ import ( "github.com/aergoio/aergo-lib/db" "github.com/aergoio/aergo/v2/internal/common" + "github.com/aergoio/aergo/v2/internal/enc/proto" "github.com/aergoio/aergo/v2/types" - "github.com/golang/protobuf/proto" ) func (states *StateDB) OpenContractStateAccount(aid types.AccountID) (*ContractState, error) { @@ -192,7 +192,7 @@ func (st *ContractState) Hash() []byte { // Marshal implements types.ImplMarshal func (st *ContractState) Marshal() ([]byte, error) { - return proto.Marshal(st.State) + return proto.Encode(st.State) } func (st *ContractState) cache() *stateBuffer { diff --git a/state/statebuffer.go b/state/statebuffer.go index 0ea32c8e5..b2a369e3a 100644 --- a/state/statebuffer.go +++ b/state/statebuffer.go @@ -4,9 +4,9 @@ import ( "sort" "github.com/aergoio/aergo/v2/internal/common" + "github.com/aergoio/aergo/v2/internal/enc/proto" "github.com/aergoio/aergo/v2/pkg/trie" "github.com/aergoio/aergo/v2/types" - "github.com/golang/protobuf/proto" ) type entry interface { @@ -205,7 +205,7 @@ func marshal(data interface{}) ([]byte, error) { case (types.ImplMarshal): return data.(types.ImplMarshal).Marshal() case (proto.Message): - return proto.Marshal(data.(proto.Message)) + return proto.Encode(data.(proto.Message)) } return nil, nil } diff --git a/state/statedata.go b/state/statedata.go index 5522ce125..2c4f47478 100644 --- a/state/statedata.go +++ b/state/statedata.go @@ -3,8 +3,8 @@ package state import ( "github.com/aergoio/aergo-lib/db" "github.com/aergoio/aergo/v2/internal/enc/gob" + "github.com/aergoio/aergo/v2/internal/enc/proto" "github.com/aergoio/aergo/v2/types" - "github.com/golang/protobuf/proto" ) func saveData(store db.DB, key []byte, data interface{}) error { @@ -17,7 +17,7 @@ func saveData(store db.DB, key []byte, data interface{}) error { case ([]byte): raw = data.([]byte) case proto.Message: - raw, err = proto.Marshal(data.(proto.Message)) + raw, err = proto.Encode(data.(proto.Message)) if err != nil { return err } @@ -45,7 +45,7 @@ func loadData(store db.DB, key []byte, data interface{}) error { case *[]byte: *(data).(*[]byte) = raw case proto.Message: - err = proto.Unmarshal(raw, data.(proto.Message)) + err = proto.Decode(raw, data.(proto.Message)) default: err = gob.Decode(raw, data) } diff --git a/tools/mpdumpdiag/main.go b/tools/mpdumpdiag/main.go index 14f98adc8..56d5608e9 100644 --- a/tools/mpdumpdiag/main.go +++ b/tools/mpdumpdiag/main.go @@ -9,8 +9,8 @@ import ( "os" "github.com/aergoio/aergo/v2/cmd/aergocli/util" + "github.com/aergoio/aergo/v2/internal/enc/proto" "github.com/aergoio/aergo/v2/types" - "github.com/golang/protobuf/proto" "github.com/spf13/cobra" ) @@ -75,7 +75,7 @@ func runPrintCmd(cmd *cobra.Command, args []string) { break } - err = proto.Unmarshal(buffer, &buf) + err = proto.Decode(buffer, &buf) if err != nil { cmd.Println("error: unmarshall tx err, continue", err.Error()) continue @@ -112,7 +112,7 @@ func runGenCmd(cmd *cobra.Command, args []string) { txlist, err := util.ParseBase58Tx(b) for _, v := range txlist { var total_data []byte - data, err := proto.Marshal(v) + data, err := proto.Encode(v) if err != nil { cmd.Println("error: marshal failed", err.Error()) continue diff --git a/types/blockchain.go b/types/blockchain.go index 27c938df4..e4905dc54 100644 --- a/types/blockchain.go +++ b/types/blockchain.go @@ -18,8 +18,8 @@ import ( "github.com/aergoio/aergo/v2/internal/common" "github.com/aergoio/aergo/v2/internal/enc/base58" + "github.com/aergoio/aergo/v2/internal/enc/proto" "github.com/aergoio/aergo/v2/internal/merkle" - "github.com/golang/protobuf/proto" "github.com/libp2p/go-libp2p-core/crypto" "github.com/minio/sha256-simd" ) diff --git a/types/blockchain_test.go b/types/blockchain_test.go index 88db63786..643f992fc 100644 --- a/types/blockchain_test.go +++ b/types/blockchain_test.go @@ -7,7 +7,7 @@ import ( "testing" "time" - "github.com/golang/protobuf/proto" + "github.com/aergoio/aergo/v2/internal/enc/proto" "github.com/libp2p/go-libp2p-core/crypto" "github.com/minio/sha256-simd" "github.com/stretchr/testify/assert" diff --git a/types/p2p_test.go b/types/p2p_test.go index fd3747f69..ebd5d3106 100644 --- a/types/p2p_test.go +++ b/types/p2p_test.go @@ -11,7 +11,7 @@ import ( "github.com/aergoio/aergo/v2/internal/enc/base58" "github.com/aergoio/aergo/v2/internal/enc/hex" - "github.com/golang/protobuf/proto" + "github.com/aergoio/aergo/v2/internal/enc/proto" "github.com/stretchr/testify/assert" ) @@ -22,7 +22,7 @@ func TestUnmarshalSize(t *testing.T) { sample := &NewTransactionsNotice{} expectedLen := proto.Size(sample) - actual, err := proto.Marshal(sample) + actual, err := proto.Encode(sample) assert.Nil(t, err) fmt.Println("Empty notice size ", len(actual)) assert.Equal(t, expectedLen, len(actual)) @@ -32,7 +32,7 @@ func TestUnmarshalSize(t *testing.T) { hashes = append(hashes, dummyTxHash) sample.TxHashes = hashes expectedLen = proto.Size(sample) - actual, err = proto.Marshal(sample) + actual, err = proto.Encode(sample) assert.Nil(t, err) fmt.Println("Single hash notice size ", len(actual)) fmt.Println("Hex: ", hex.Encode(actual)) @@ -45,7 +45,7 @@ func TestUnmarshalSize(t *testing.T) { } sample.TxHashes = hashes expectedLen = proto.Size(sample) - actual, err = proto.Marshal(sample) + actual, err = proto.Encode(sample) assert.Nil(t, err) fmt.Println("Hundred hashes notice size ", len(actual)) fmt.Println("Hex: ", hex.Encode(actual[0:40])) @@ -58,7 +58,7 @@ func TestUnmarshalSize(t *testing.T) { } sample.TxHashes = hashes expectedLen = proto.Size(sample) - actual, err = proto.Marshal(sample) + actual, err = proto.Encode(sample) assert.Nil(t, err) fmt.Println("Thousand hashes notice size ", len(actual)) fmt.Println("Hex: ", hex.Encode(actual[0:40])) diff --git a/types/transaction.go b/types/transaction.go index 17cbeb80c..ae88e8789 100644 --- a/types/transaction.go +++ b/types/transaction.go @@ -9,7 +9,7 @@ import ( "github.com/aergoio/aergo/v2/fee" "github.com/aergoio/aergo/v2/internal/enc/base58" - "github.com/golang/protobuf/proto" + "github.com/aergoio/aergo/v2/internal/enc/proto" ) //governance type transaction which has aergo.system in recipient