diff --git a/account/key/crypto/v1strategy.go b/account/key/crypto/v1strategy.go index 6e6c2d9e4..d4a8a32ac 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/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: hex.EncodeToString(iv), + Iv: hex.Encode(iv), }, - Ciphertext: hex.EncodeToString(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: hex.EncodeToString(salt), + Salt: hex.Encode(salt), }, - Mac: hex.EncodeToString(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 := hex.DecodeString(kdf.Mac) + mac, err := hex.Decode(kdf.Mac) if nil != err { return nil, err } - cipherText, err := hex.DecodeString(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 := hex.DecodeString(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 := hex.DecodeString(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 3fa07fb91..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.ToString(t.src), enc.ToString(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.ToString(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.ToString(hdrRootHash)). - Str("compute txroot", enc.ToString(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.ToString(hdrRoot)). - Str("sdbroot", enc.ToString(sdbRoot)). + Str("hdrroot", base58.Encode(hdrRoot)). + Str("sdbroot", base58.Encode(sdbRoot)). Msg("block root hash validation failed") return ErrorBlockVerifyStateRoot } - logger.Debug().Str("sdbroot", enc.ToString(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.ToString(hdrRoot)). - Str("receipts_root", enc.ToString(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.ToString(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 a29455879..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.ToString(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.ToString(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 a846444cd..52b50495c 100644 --- a/chain/chaindb.go +++ b/chain/chaindb.go @@ -7,7 +7,6 @@ package chain import ( "bytes" - "encoding/gob" "encoding/json" "errors" "fmt" @@ -17,10 +16,11 @@ 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/internal/enc/proto" "github.com/aergoio/aergo/v2/types" "github.com/aergoio/aergo/v2/types/dbkey" - "github.com/golang/protobuf/proto" ) var ( @@ -45,7 +45,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", base58.Encode(id)) default: idStr = fmt.Sprintf("blockNo=%v", id) } @@ -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)) } @@ -445,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.ToString(blockHash)).Int("txidx", i). + logger.Error().Err(err).Str("hash", base58.Encode(blockHash)).Int("txidx", i). Msg("failed to add tx") return err @@ -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 @@ -611,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.ToString(txHash)) + return nil, nil, fmt.Errorf("tx not found: txHash=%v", base58.Encode(txHash)) } block, err := cdb.getBlock(txIdx.BlockHash) if err != nil { @@ -622,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.ToString(txHash)).Msg("getTx") + logger.Debug().Str("hash", base58.Encode(txHash)).Msg("getTx") return tx, txIdx, nil } @@ -649,13 +649,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 := gob.Decode(data, &receipts) return &receipts, err } @@ -683,9 +680,9 @@ func (cdb *ChainDB) GetChainTree() ([]byte, error) { hash, _ := cdb.getHashByNo(i) tree = append(tree, ChainInfo{ Height: i, - Hash: enc.ToString(hash), + Hash: base58.Encode(hash), }) - logger.Info().Str("hash", enc.ToString(hash)).Msg("GetChainTree") + logger.Info().Str("hash", base58.Encode(hash)).Msg("GetChainTree") } jsonBytes, err := json.Marshal(tree) if err != nil { @@ -698,11 +695,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, _ := gob.Encode(receipts) + dbTx.Set(dbkey.Receipts(blockHash, blockNo), val) dbTx.Commit() } @@ -743,10 +737,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 := gob.Decode(data, &marker) return &marker, err } diff --git a/chain/chaindbForRaft.go b/chain/chaindbForRaft.go index 49d71c045..5f18f18ed 100644 --- a/chain/chaindbForRaft.go +++ b/chain/chaindbForRaft.go @@ -1,16 +1,15 @@ 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/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 ( @@ -127,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) @@ -144,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") } @@ -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 := gob.Decode(data, &entry); err != nil { return nil, err } @@ -358,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 } @@ -406,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 } @@ -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 := gob.Encode(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 := gob.Decode(data, &id); err != nil { return nil, ErrDecodeRaftIdentity } @@ -480,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 } @@ -498,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 70024bffe..be972b577 100644 --- a/chain/chainhandle.go +++ b/chain/chainhandle.go @@ -18,11 +18,11 @@ 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/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 ( @@ -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(), 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.ToString(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.ToString(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.ToString(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.ToString(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.ToString(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 3504758b3..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.ToString(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.ToString(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.ToString(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.ToString(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.ToString(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.ToString(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.ToString(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.ToString(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.ToString(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.ToString(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 bd5bc4fc2..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.ToString(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.ToString(targetBlock.GetHeader().GetTxsRootHash())) - report += fmt.Sprintf(", state Root = %s", enc.ToString(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 fccd0ec9c..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.ToString(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 1e254fcb7..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.ToString(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 af70d54de..26e14ee74 100644 --- a/chain/recover.go +++ b/chain/recover.go @@ -2,14 +2,14 @@ package chain import ( "bytes" - "encoding/gob" "errors" "fmt" "os" "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" ) @@ -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", base58.Encode(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 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.ToString(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.ToString(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.ToString(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 53ce6f3d2..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.ToString(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 b3b65edab..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.ToString(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 112fb0dc2..271f32234 100644 --- a/cmd/aergocli/cmd/blockchain_test.go +++ b/cmd/aergocli/cmd/blockchain_test.go @@ -1,13 +1,13 @@ package cmd import ( - "encoding/hex" "testing" "github.com/aergoio/aergo/v2/cmd/aergocli/util/encoding/json" + "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/mr-tron/base58/base58" "github.com/stretchr/testify/assert" ) @@ -49,6 +49,6 @@ func TestBlockchainWithMock(t *testing.T) { t.Fatal(err) } testBlockHashByte, _ := base58.Decode(testBlockHashString) - assert.Equal(t, hex.EncodeToString(testBlockHashByte), result["Hash"]) + 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 27f3de136..aa5eb00fd 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/base58" "github.com/aergoio/aergo/v2/types" "github.com/golang/mock/gomock" - "github.com/mr-tron/base58/base58" "github.com/stretchr/testify/assert" ) diff --git a/cmd/aergocli/cmd/contract.go b/cmd/aergocli/cmd/contract.go index 0e8bbb2aa..010b7f6ac 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" @@ -14,9 +13,10 @@ 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/base58" + "github.com/aergoio/aergo/v2/internal/enc/hex" "github.com/aergoio/aergo/v2/types" aergorpc "github.com/aergoio/aergo/v2/types" - "github.com/mr-tron/base58/base58" "github.com/spf13/cobra" ) @@ -201,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 = hex.DecodeString(data) + payload, err = hex.Decode(data) } else { // the data is the output of aergoluac code, err = luacEncoding.DecodeCode(data) diff --git a/cmd/aergocli/cmd/enterprise.go b/cmd/aergocli/cmd/enterprise.go index ad24bfd40..ed57846d4 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/base58" "github.com/aergoio/aergo/v2/types" aergorpc "github.com/aergoio/aergo/v2/types" - "github.com/mr-tron/base58/base58" "github.com/spf13/cobra" ) diff --git a/cmd/aergocli/cmd/enterprise_test.go b/cmd/aergocli/cmd/enterprise_test.go index 09737e07b..a9ddd1faf 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/base58" aergorpc "github.com/aergoio/aergo/v2/types" "github.com/golang/mock/gomock" - "github.com/mr-tron/base58/base58" "github.com/stretchr/testify/assert" ) diff --git a/cmd/aergocli/cmd/getblock.go b/cmd/aergocli/cmd/getblock.go index 6f29340b0..f54e43dbb 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/base58" aergorpc "github.com/aergoio/aergo/v2/types" - "github.com/mr-tron/base58/base58" "github.com/spf13/cobra" ) diff --git a/cmd/aergocli/cmd/getstate.go b/cmd/aergocli/cmd/getstate.go index a2b02c3eb..7e3080523 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/base58" "github.com/aergoio/aergo/v2/types" - "github.com/mr-tron/base58/base58" "github.com/spf13/cobra" ) diff --git a/cmd/aergocli/cmd/gettx.go b/cmd/aergocli/cmd/gettx.go index a9f7f8d8e..a122aec0c 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/base58" aergorpc "github.com/aergoio/aergo/v2/types" - "github.com/mr-tron/base58/base58" "github.com/spf13/cobra" ) diff --git a/cmd/aergocli/cmd/keygen.go b/cmd/aergocli/cmd/keygen.go index 8d6a323e9..ef553d154 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/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: b64.StdEncoding.EncodeToString(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 d20a32385..aa4c1c003 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/base58" "github.com/aergoio/aergo/v2/types" - "github.com/mr-tron/base58/base58" "github.com/spf13/cobra" ) diff --git a/cmd/aergocli/cmd/receipt.go b/cmd/aergocli/cmd/receipt.go index fc7d8fefe..c36945556 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/base58" aergorpc "github.com/aergoio/aergo/v2/types" - "github.com/mr-tron/base58/base58" "github.com/spf13/cobra" ) diff --git a/cmd/aergocli/cmd/sendtx.go b/cmd/aergocli/cmd/sendtx.go index f76923ba7..0b01d7df6 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/base58" "github.com/aergoio/aergo/v2/types" - "github.com/mr-tron/base58" "github.com/spf13/cobra" ) diff --git a/cmd/aergocli/cmd/sendtx_test.go b/cmd/aergocli/cmd/sendtx_test.go index 5cb101dac..cec44f02e 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/base58" "github.com/aergoio/aergo/v2/types" "github.com/golang/mock/gomock" - "github.com/mr-tron/base58/base58" "github.com/stretchr/testify/assert" ) diff --git a/cmd/aergocli/cmd/signtx.go b/cmd/aergocli/cmd/signtx.go index d4e8b48db..748784ff1 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/base58" "github.com/aergoio/aergo/v2/types" "github.com/btcsuite/btcd/btcec" - "github.com/mr-tron/base58/base58" "github.com/spf13/cobra" ) diff --git a/cmd/aergocli/cmd/signtx_test.go b/cmd/aergocli/cmd/signtx_test.go index e76a37b52..972aca344 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/base58" "github.com/aergoio/aergo/v2/types" - "github.com/mr-tron/base58/base58" "github.com/stretchr/testify/assert" ) diff --git a/cmd/aergocli/cmd/vote.go b/cmd/aergocli/cmd/vote.go index 880980b9c..122c35441 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/base58" "github.com/aergoio/aergo/v2/types" - "github.com/mr-tron/base58/base58" "github.com/spf13/cobra" ) diff --git a/cmd/aergocli/util/base58addr.go b/cmd/aergocli/util/base58addr.go index 90993c03a..c744d6591 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/base58" "github.com/aergoio/aergo/v2/p2p/p2putil" "github.com/aergoio/aergo/v2/types" - "github.com/mr-tron/base58/base58" ) type InOutBlockHeader struct { diff --git a/cmd/aergocli/util/base58addr_test.go b/cmd/aergocli/util/base58addr_test.go index a3f962b98..ec6800c28 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/base58" "github.com/aergoio/aergo/v2/types" - "github.com/mr-tron/base58/base58" "github.com/stretchr/testify/assert" ) diff --git a/cmd/aergocli/util/base64ToHex.go b/cmd/aergocli/util/base64ToHex.go index 0df49c088..6ce5d33aa 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/hex" "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 = hex.Encode(in.BestBlockHash) out.Height = in.BestHeight - out.ChainIdHash = hex.EncodeToString(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 9fd2838d3..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/mr-tron/base58/base58" + "github.com/aergoio/aergo/v2/internal/enc/base58" ) // Unmarshal parses the JSON-encoded data and stores the result diff --git a/cmd/aergocli/util/encoding/json/encode.go b/cmd/aergocli/util/encoding/json/encode.go index 337129a21..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/mr-tron/base58/base58" + "github.com/aergoio/aergo/v2/internal/enc/base58" ) // Marshal returns the JSON encoding of v. 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/aergoluac/encoding/codeEncoding.go b/cmd/aergoluac/encoding/codeEncoding.go index a2e850158..75329ed98 100644 --- a/cmd/aergoluac/encoding/codeEncoding.go +++ b/cmd/aergoluac/encoding/codeEncoding.go @@ -1,17 +1,17 @@ package encoding import ( - "encoding/hex" "errors" "fmt" - "github.com/anaskhan96/base58check" + "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, _ := base58check.Encode(fmt.Sprintf("%x", CodeVersion), hex.EncodeToString(code)) + encoded, _ := base58check.Encode(fmt.Sprintf("%x", CodeVersion), hex.Encode(code)) return encoded } @@ -20,7 +20,7 @@ func DecodeCode(encodedCode string) ([]byte, error) { if err != nil { return nil, err } - decodedBytes, err := hex.DecodeString(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 b88a9c0a4..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.ToString(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.ToString(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/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/cmd/colaris/cmd/current.go b/cmd/colaris/cmd/current.go index 4d971f197..ef96bc018 100644 --- a/cmd/colaris/cmd/current.go +++ b/cmd/colaris/cmd/current.go @@ -10,9 +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/base58" "github.com/aergoio/aergo/v2/types" "github.com/spf13/cobra" ) diff --git a/consensus/chain/block.go b/consensus/chain/block.go index d81aa4649..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.ToString(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.ToString(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.ToString(targetHash)). + Str("hash", base58.Encode(targetHash)). Msg("failed to sync") return err 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/dpos/blockfactory.go b/consensus/impl/dpos/blockfactory.go index f8ee9ca7b..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.ToString(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.ToString(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 00447e060..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/common" + "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 := common.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 a9a675e5d..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/common" + "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 := common.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 := common.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 0128398f8..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.ToString(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.ToString(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 55b0baf67..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.ToString(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 2cf27b7cb..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.ToString([]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.ToString(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.ToString(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.ToString(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/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/consensus/impl/sbp/sbp.go b/consensus/impl/sbp/sbp.go index a8ef44cc0..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.ToString(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 4bcbd42f4..eefd26d5b 100644 --- a/consensus/raftCommon.go +++ b/consensus/raftCommon.go @@ -5,13 +5,13 @@ import ( "context" "crypto/sha1" "encoding/binary" - "encoding/gob" "encoding/json" "errors" "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" @@ -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 gob.Encode(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, base58.Encode(csnap.Hash)) } /* diff --git a/contract/enterprise/validate.go b/contract/enterprise/validate.go index 1e95a42f3..9001362f0 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/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 := base64.StdEncoding.DecodeString(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 da50b9902..018c8e9a1 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/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(hex.EncodeToString(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(hex.EncodeToString(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 hex.EncodeToString(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 e87de30a7..9da60d342 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/hex" ) 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, _ := hex.Decode(removeHexPrefix(s)) return n } func proofToBytes(proof []string) [][]byte { var r [][]byte for _, n := range proof { - d, err := hex.DecodeString(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 72f6a05e0..72fba8aba 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/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 := hex.DecodeString(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 hex.EncodeToString(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 d5fd02547..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.ToBytes(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 b971c414a..a785ac674 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/base58" "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. diff --git a/contract/system/execute_test.go b/contract/system/execute_test.go index 6f1f8acff..479c75951 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/base58" "github.com/aergoio/aergo/v2/types" - "github.com/mr-tron/base58/base58" "github.com/stretchr/testify/assert" ) diff --git a/contract/system/vote.go b/contract/system/vote.go index cf5f9e083..afee0a0ac 100644 --- a/contract/system/vote.go +++ b/contract/system/vote.go @@ -12,11 +12,10 @@ 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" - "github.com/mr-tron/base58" ) const ( @@ -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 := base58.Encode(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, base58.Encode(v.Candidate)) } return bps, nil } diff --git a/contract/system/vote_test.go b/contract/system/vote_test.go index 8eff82f3b..0d8bb233b 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/base58" "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" ) diff --git a/contract/system/voteresult.go b/contract/system/voteresult.go index b183f5fa3..386726de9 100644 --- a/contract/system/voteresult.go +++ b/contract/system/voteresult.go @@ -8,11 +8,10 @@ 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" - "github.com/mr-tron/base58" ) type VoteResult struct { @@ -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, _ = base58.Decode(k) } voteList.Votes = append(voteList.Votes, vote) } diff --git a/contract/system/vprt.go b/contract/system/vprt.go index 09009c9ab..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.ToString(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.ToString(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.ToString(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 2cd9582b3..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.ToString(vprStateDB.GetRoot()), - enc.ToString(s.GetStorageRoot())) + base58.Encode(vprStateDB.GetRoot()), + base58.Encode(s.GetStorageRoot())) return s } diff --git a/contract/vm.go b/contract/vm.go index 9bd1442c8..ad669675f 100644 --- a/contract/vm.go +++ b/contract/vm.go @@ -22,7 +22,6 @@ import "C" import ( "bytes" "context" - "encoding/hex" "encoding/json" "errors" "fmt" @@ -39,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" @@ -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", base58.Encode(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(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()) } @@ -1459,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(hex.EncodeToString(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 5cf046388..7613a960d 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" @@ -39,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" @@ -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(base58.Encode(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(base58.Encode(ctx.blockInfo.PrevBlockHash)) } //export luaGetDbHandle @@ -871,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 = hex.DecodeString(string(dataStr)) + data, err = hex.Decode(string(dataStr)) if err != nil { return nil, C.CString("[Contract.LuaCryptoSha256] hex decoding error: " + err.Error()) } @@ -880,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" + hex.EncodeToString(resultHash)), nil + return C.CString("0x" + hex.Encode(resultHash)), nil } func decodeHex(hexStr string) ([]byte, error) { if checkHexString(hexStr) { hexStr = hexStr[2:] } - return hex.DecodeString(hexStr) + return hex.Decode(hexStr) } //export luaECVerify @@ -971,7 +971,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 = hex.Decode(string(b[2:])) if err != nil { isHex = false } @@ -1023,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" + hex.EncodeToString(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 3fefe9585..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.ToString(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.ToString(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.ToString(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.ToString(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 c1fbce3c6..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.ToString(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/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/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/bstr_test.go b/internal/enc/base58/base58_test.go similarity index 86% rename from internal/enc/bstr_test.go rename to internal/enc/base58/base58_test.go index 8ebf31c7c..dfe96e6af 100644 --- a/internal/enc/bstr_test.go +++ b/internal/enc/base58/base58_test.go @@ -1,11 +1,11 @@ -package enc +package base58 import ( "bytes" "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 := Encode(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 := Decode(got) if err != nil { t.Errorf("ToBytes() = %s, want no err", err.Error()) } 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/base58check_test.go b/internal/enc/base58check/base58check_test.go new file mode 100644 index 000000000..dc8e9ac10 --- /dev/null +++ b/internal/enc/base58check/base58check_test.go @@ -0,0 +1,31 @@ +package base58check + +import ( + "testing" + + "github.com/aergoio/aergo/v2/internal/enc/hex" + "github.com/stretchr/testify/require" +) + +func TestB58CheckEncode(t *testing.T) { + for _, test := range []struct { + name string + version string + data string + expect string + }{ + {"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 := 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 := 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/base64.go b/internal/enc/base64/base64.go new file mode 100644 index 000000000..999484323 --- /dev/null +++ b/internal/enc/base64/base64.go @@ -0,0 +1,17 @@ +package base64 + +import "encoding/base64" + +func Encode(s []byte) string { + return base64.StdEncoding.EncodeToString(s) +} + +func Decode(s string) ([]byte, error) { + return base64.StdEncoding.DecodeString(s) +} + +// Do not use processing real data, Only use for Logging or Testing. +func DecodeOrNil(s string) []byte { + buf, _ := Decode(s) + return buf +} 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/enc/gob/gob.go b/internal/enc/gob/gob.go new file mode 100644 index 000000000..be2baa1c5 --- /dev/null +++ b/internal/enc/gob/gob.go @@ -0,0 +1,22 @@ +package gob + +import ( + "bytes" + "encoding/gob" +) + +// 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 { + return nil, err + } + return buf.Bytes(), nil +} + +// 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/gob_test.go b/internal/enc/gob/gob_test.go new file mode 100644 index 000000000..b4300cabc --- /dev/null +++ b/internal/enc/gob/gob_test.go @@ -0,0 +1,23 @@ +package gob + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestGobCodec(t *testing.T) { + a := assert.New(t) + + x := []int{1, 2, 3} + b, err := Encode(x) + a.Nil(err) + + y := []int{0, 0, 0} + err = Decode(b, &y) + a.Nil(err) + + for i, v := range x { + a.Equal(v, y[i]) + } +} 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/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/internal/merkle/merkle_test.go b/internal/merkle/merkle_test.go index 56d1c477f..7a8d0a68c 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/base64" "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, base64.Encode(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, base64.Encode(merkle)) } } diff --git a/mempool/mempool.go b/mempool/mempool.go index 9a4577301..1599a6736 100644 --- a/mempool/mempool.go +++ b/mempool/mempool.go @@ -28,12 +28,12 @@ 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/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 ( @@ -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", 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.ToString(mp.bestChainIdHash)). - Str("next chainidhash", enc.ToString(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.ToString(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") @@ -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 @@ -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", 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.ToString(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 76f3e9745..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.ToString(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 84343c4bc..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.ToString(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.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", 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 b126be5c8..0d53fdbcf 100644 --- a/p2p/const_test.go +++ b/p2p/const_test.go @@ -7,13 +7,13 @@ package p2p import ( "bytes" - "encoding/base64" - "encoding/hex" "fmt" "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" @@ -23,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, _ = hex.DecodeString("4f461d85e869ade8a0544f8313987c33a9c06534e50c4ad941498299579bd7ac") +var dummyBlockHash, _ = hex.Decode("4f461d85e869ade8a0544f8313987c33a9c06534e50c4ad941498299579bd7ac") var dummyBlockHeight uint64 = 100215 -var dummyTxHash, _ = enc.ToBytes("4H4zAkAyRV253K5SNBJtBxqUgHEbZcXbWFFc6cmQHY45") +var dummyTxHash, _ = base58.Decode("4H4zAkAyRV253K5SNBJtBxqUgHEbZcXbWFFc6cmQHY45") var samplePeerID types.PeerID var sampleMeta p2pcommon.PeerMeta @@ -67,9 +67,9 @@ var dummyBestBlock *types.Block var dummyMeta p2pcommon.PeerMeta func init() { - bytes, _ := base64.StdEncoding.DecodeString(sampleKey1PrivBase64) + bytes, _ := base64.Decode(sampleKey1PrivBase64) sampleKey1Priv, _ = crypto.UnmarshalPrivateKey(bytes) - bytes, _ = base64.StdEncoding.DecodeString(sampelKey1PubBase64) + bytes, _ = base64.Decode(sampelKey1PubBase64) sampleKey1Pub, _ = crypto.UnmarshalPublicKey(bytes) if !sampleKey1Priv.GetPublic().Equals(sampleKey1Pub) { panic("problem in pk generation ") @@ -79,7 +79,7 @@ func init() { panic("problem in id generation") } - bytes, _ = base64.StdEncoding.DecodeString(sampleKey2PrivBase64) + bytes, _ = base64.Decode(sampleKey2PrivBase64) sampleKey2Priv, _ = crypto.UnmarshalPrivateKey(bytes) sampleKey2Pub = sampleKey2Priv.GetPublic() sampleKey2ID, _ = types.IDFromPublicKey(sampleKey2Pub) @@ -121,7 +121,7 @@ func init() { sampleTxs = make([][]byte, len(sampleTxsB58)) sampleTxIDs = make([]types.TxID, len(sampleTxsB58)) for i, hashb58 := range sampleTxsB58 { - hash, _ := enc.ToBytes(hashb58) + hash, _ := base58.Decode(hashb58) sampleTxs[i] = hash copy(sampleTxIDs[i][:], hash) } @@ -129,7 +129,7 @@ func init() { sampleBlks = make([][]byte, len(sampleBlksB58)) sampleBlksIDs = make([]types.BlockID, len(sampleBlksB58)) for i, hashb58 := range sampleTxsB58 { - hash, _ := enc.ToBytes(hashb58) + hash, _ := base58.Decode(hashb58) sampleBlks[i] = hash copy(sampleBlksIDs[i][:], hash) } @@ -149,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.ToString(sampleTxs[i]), sampleTxIDs[i]) + t.Errorf("TX hash %v and converted ID %v are differ.", base58.Encode(sampleTxs[i]), sampleTxIDs[i]) } } } @@ -157,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.ToString(sampleBlks[i]), sampleBlksIDs[i]) + t.Errorf("TX hash %v and converted ID %v are differ.", base58.Encode(sampleBlks[i]), sampleBlksIDs[i]) } } } @@ -267,12 +267,12 @@ var testIn = []string{ func TestMoreTXIDs(t *testing.T) { for _, in := range testIn { - hash, _ := enc.ToBytes(in) + hash, _ := base58.Decode(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", base58.Encode(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.", base58.Encode(hash), id) } } } diff --git a/p2p/hashreceiver_test.go b/p2p/hashreceiver_test.go index ecda5f4e4..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.ToString(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 5a62a9b84..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.ToString(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/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/p2pkey/nodekey.go b/p2p/p2pkey/nodekey.go index 90dd90d16..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.ToString([]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 8a7a17477..6cb233c70 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/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", hex.EncodeToString(oldBytes)) - t.Logf("RAW %v", hex.EncodeToString(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", hex.EncodeToString(oldBytes)) - t.Logf("PUBLIC %v", hex.EncodeToString(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 11d58d261..edfb2701c 100644 --- a/p2p/p2putil/certificate_test.go +++ b/p2p/p2putil/certificate_test.go @@ -6,11 +6,11 @@ import ( "testing" "time" - "github.com/aergoio/aergo/v2/internal/enc" + "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) { @@ -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", 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.ToString(h11), enc.ToString(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.ToString(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 c09b3cc7d..07e192f99 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/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", hex.EncodeToString(raw), hex.EncodeToString(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", hex.EncodeToString(rev.Serialize()), hex.EncodeToString(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", hex.EncodeToString(raw), hex.EncodeToString(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", hex.EncodeToString(rev.SerializeCompressed()), hex.EncodeToString(pubKey.SerializeCompressed())) + t.Errorf("ConvertPubKeyToBTCEC() pk = %v, want %v", hex.Encode(rev.SerializeCompressed()), hex.Encode(pubKey.SerializeCompressed())) } }) } 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 cc3e10d04..2e918e44a 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/internal/enc/proto" "github.com/aergoio/aergo/v2/types" - "github.com/golang/protobuf/proto" "github.com/stretchr/testify/assert" ) -var dummyTxHash, _ = enc.ToBytes("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) + 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.EncodeToString(txMarshaled)) - emptyMarshaled, _ := proto.Marshal(&types.GetTransactionsResponse{}) + //fmt.Println("TX : ",hex.HexEncode(txMarshaled)) + emptyMarshaled, _ := proto.Encode(&types.GetTransactionsResponse{}) emptySize := len(emptyMarshaled) - //fmt.Println("EMPTY: ",hex.EncodeToString(emptyMarshaled)) + //fmt.Println("EMPTY: ",hex.HexEncode(emptyMarshaled)) //fmt.Printf("Size of All nil: %d , tx size: %d ",emptySize, txSize) tests := []struct { name string @@ -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()) } @@ -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: ",hex.HexEncode(actual[:cut])) assert.Equal(t, test.expectedSize, actualSize) diff --git a/p2p/p2putil/util.go b/p2p/p2putil/util.go index 539378821..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.ToString(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.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, 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 b077f1efe..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.ToString(test.in) + got := base58.Encode(test.in) assert.Equal(t, test.out, got) if len(test.out) > 0 { - gotBytes, err := enc.ToBytes(test.out) + gotBytes, err := base58.Decode(test.out) assert.Nil(t, err) assert.Equal(t, test.in, gotBytes) } 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/block.go b/p2p/subproto/block.go index 79c602ea2..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.ToString(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.ToString(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 4dba77a74..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.ToBytes(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.ToBytes(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 5cf90f2f1..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.ToString(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.ToString(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 d0e07a7d9..a6411f0de 100644 --- a/p2p/subproto/bp_test.go +++ b/p2p/subproto/bp_test.go @@ -10,13 +10,13 @@ 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/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" ) @@ -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, _ := 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 4d96e1aee..be3042131 100644 --- a/p2p/subproto/getblock.go +++ b/p2p/subproto/getblock.go @@ -9,11 +9,11 @@ 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/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 { @@ -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, 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.ToString(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 2204087f9..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.ToBytes("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.ToBytes(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 b6526aa4f..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.ToBytes("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 23c3fb9c5..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.ToString(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 d928f8e77..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.ToString(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 be9668aec..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.ToString(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.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/synctx_test.go b/p2p/synctx_test.go index fed5988d7..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.ToString(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.ToString(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.ToBytes(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 be2b8e1f1..0209773c8 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/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, _ = hex.DecodeString("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 94c956410..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.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", 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 fa1d02fae..109d52c48 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/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, _ = hex.DecodeString("4f461d85e869ade8a0544f8313987c33a9c06534e50c4ad941498299579bd7ac") + dummyBlockHash, _ = hex.Decode("4f461d85e869ade8a0544f8313987c33a9c06534e50c4ad941498299579bd7ac") dummyBlockHeight uint64 = 100215 ) diff --git a/p2p/v030/v030io_test.go b/p2p/v030/v030io_test.go index e114d0034..ca0f930c8 100644 --- a/p2p/v030/v030io_test.go +++ b/p2p/v030/v030io_test.go @@ -13,11 +13,11 @@ import ( "testing" "time" - "github.com/aergoio/aergo/v2/internal/enc" + "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" ) @@ -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, _ := 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.ToBytes(hashb58) + hash, _ := base58.Decode(hashb58) sampleBlks[i] = hash copy(sampleBlksHashes[i][:], hash) } @@ -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/p2p/v030/v032handshake.go b/p2p/v030/v032handshake.go index 803bffc7f..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.ToString(genHash), enc.ToString(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 ab5399fdf..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.ToString(genHash), enc.ToString(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 9f35813ef..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.ToString(genHash), enc.ToString(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 072195921..283ec7846 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/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, _ = hex.DecodeString("4f461d85e869ade8a0544f8313987c33a9c06534e50c4ad941498299579bd7ac") + dummyBlockHash, _ = hex.Decode("4f461d85e869ade8a0544f8313987c33a9c06534e50c4ad941498299579bd7ac") dummyBlockID = types.MustParseBlockID(dummyBlockHash) dummyBlockHeight uint64 = 100215 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/rpc/grpcserver_test.go b/rpc/grpcserver_test.go index 928d88802..f0aad80b9 100644 --- a/rpc/grpcserver_test.go +++ b/rpc/grpcserver_test.go @@ -6,14 +6,15 @@ package rpc import ( "context" - "encoding/hex" "fmt" "math/big" "reflect" "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" @@ -21,38 +22,37 @@ 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("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", hex.EncodeToString(dummyTxHash)) - fmt.Printf("B64 : %s \n", enc.ToString(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", hex.EncodeToString(dummyWalletAddress)) - fmt.Printf("B64 : %s \n", enc.ToString(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", hex.EncodeToString(dummyWalletAddress2)) - fmt.Printf("B64 : %s \n", enc.ToString(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, _ = hex.DecodeString("4f461d85e869ade8a0544f8313987c33a9c06534e50c4ad941498299579bd7ac") +var dummyBlockHash, _ = hex.Decode("4f461d85e869ade8a0544f8313987c33a9c06534e50c4ad941498299579bd7ac") var dummyBlockHeight uint32 = 100215 -var dummyTxHash, _ = hex.DecodeString("218bdab4e87fb332b55eb89854ef553f9e3d440c81fff4161b672adede1261ee") +var dummyTxHash, _ = hex.Decode("218bdab4e87fb332b55eb89854ef553f9e3d440c81fff4161b672adede1261ee") // base64 encoding of dummyTxHash is "" var dummyWalletAddress, _ = base58.Decode("1Ee8uhLFXzkSRRU1orBpgXFAPpVi64aSYo") diff --git a/state/chainstatedb.go b/state/chainstatedb.go index dd5a00eba..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.ToString(sdb.states.GetRoot())). - Str("stateRoot", enc.ToString(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.ToString(sdb.states.GetRoot())). - Str("target", enc.ToString(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/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/statebuffer_test.go b/state/statebuffer_test.go index 4f881eb60..56d65c1ae 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/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, hex.EncodeToString(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, hex.EncodeToString(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, hex.EncodeToString(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, hex.EncodeToString(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, hex.EncodeToString(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, hex.EncodeToString(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 d4756c603..2c4f47478 100644 --- a/state/statedata.go +++ b/state/statedata.go @@ -1,12 +1,10 @@ package state import ( - "bytes" - "encoding/gob" - "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 { @@ -19,18 +17,12 @@ 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 } default: - buffer := &bytes.Buffer{} - enc := gob.NewEncoder(buffer) - err = enc.Encode(data) - if err != nil { - return err - } - raw = buffer.Bytes() + raw, err = gob.Encode(data) if err != nil { return err } @@ -53,11 +45,9 @@ 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: - reader := bytes.NewReader(raw) - dec := gob.NewDecoder(reader) - err = dec.Decode(data) + err = gob.Decode(raw, data) } return err } diff --git a/state/statedb.go b/state/statedb.go index 5f213410b..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.ToString(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.ToString(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", hex.EncodeToString(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 2eea7404d..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.ToString(before)). - Str("after", enc.ToString(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 fbe64018c..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.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", 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.ToString(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.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", 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.ToString(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.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", 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.ToString(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.ToString(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.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", 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.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", 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.ToString(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.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", 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.ToString(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 b533bc49c..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.ToString(msg.Blocks[0].GetHash())). - Str("to", enc.ToString(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.ToString(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.ToString(curHash)).Str("msgHash", enc.ToString(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.ToString(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.ToString(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.ToString(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.ToString(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 70a179a38..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.ToString(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.ToString(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.ToString(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 3892bd130..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.ToString(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.ToString(hf.lastBlockInfo.Hash)). - Str("msg prev", enc.ToString(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.ToString(msg.Hashes[0])). - Str("end", enc.ToString(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 26de7d6ee..030cebe38 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/hex" "github.com/aergoio/aergo/v2/types" ) @@ -41,6 +41,6 @@ func main() { panic(err) } - str := "\"" + hex.EncodeToString(bs) + "\"" + str := "\"" + hex.Encode(bs) + "\"" fmt.Println(str) } 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/account.go b/types/account.go index 2512ca8cd..ecd58ef70 100644 --- a/types/account.go +++ b/types/account.go @@ -1,12 +1,12 @@ package types import ( - "encoding/hex" "errors" "fmt" "strings" - "github.com/anaskhan96/base58check" + "github.com/aergoio/aergo/v2/internal/enc/base58check" + "github.com/aergoio/aergo/v2/internal/enc/hex" ) 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, _ := base58check.Encode(fmt.Sprintf("%x", AddressVersion), hex.Encode(addr)) return encoded } @@ -72,7 +72,7 @@ func DecodeAddress(encodedAddr string) (Address, error) { if err != nil { return nil, err } - decodedBytes, err := hex.DecodeString(decodedString) + decodedBytes, err := hex.Decode(decodedString) if err != nil { return nil, err } @@ -95,7 +95,7 @@ func DecodeAddressBytes(decodedBytes []byte) (Address, error) { } func EncodePrivKey(key []byte) string { - encoded, _ := base58check.Encode(fmt.Sprintf("%x", PrivKeyVersion), hex.EncodeToString(key)) + encoded, _ := base58check.Encode(fmt.Sprintf("%x", PrivKeyVersion), hex.Encode(key)) return encoded } @@ -104,7 +104,7 @@ func DecodePrivKey(encodedKey string) ([]byte, error) { if err != nil { return nil, err } - decodedBytes, err := hex.DecodeString(decodedString) + decodedBytes, err := hex.Decode(decodedString) if err != nil { return nil, err } diff --git a/types/blockchain.go b/types/blockchain.go index 3de9e1bf3..e4905dc54 100644 --- a/types/blockchain.go +++ b/types/blockchain.go @@ -17,9 +17,9 @@ 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/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" ) @@ -452,14 +452,14 @@ func (block *Block) BPID2Str() string { return "" } - return enc.ToString([]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.ToString(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.ToString(hash) + return base58.Encode(hash) } return "" 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/common.go b/types/common.go index b25aeaa6c..8304b2e48 100644 --- a/types/common.go +++ b/types/common.go @@ -1,9 +1,8 @@ package types import ( - "encoding/base64" - - "github.com/mr-tron/base58/base58" + "github.com/aergoio/aergo/v2/internal/enc/base58" + "github.com/aergoio/aergo/v2/internal/enc/base64" ) const MAXBLOCKNO BlockNo = 18446744073709551615 @@ -11,11 +10,11 @@ const maxMetaSizeLimit = uint32(256 << 10) const blockSizeHardLimit = uint32(8 << (10 * 2)) func EncodeB64(bs []byte) string { - return base64.StdEncoding.EncodeToString(bs) + return base64.Encode(bs) } func DecodeB64(sb string) []byte { - buf, _ := base64.StdEncoding.DecodeString(sb) + buf, _ := base64.Decode(sb) return buf } diff --git a/types/genesis.go b/types/genesis.go index 4ec01695f..2d6853e44 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" @@ -11,7 +10,8 @@ import ( "strings" "time" - "github.com/aergoio/aergo/v2/internal/common" + "github.com/aergoio/aergo/v2/internal/enc/gob" + "github.com/aergoio/aergo/v2/internal/enc/hex" ) const ( @@ -281,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 := common.GobEncode(g); err == nil { + if b, err := gob.Encode(g); err == nil { return b } return nil @@ -333,7 +333,7 @@ func GetDefaultGenesis() *Genesis { } func GetMainNetGenesis() *Genesis { - if bs, err := hex.DecodeString(MainNetGenesis); err == nil { + if bs, err := hex.Decode(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 := hex.Decode(TestNetGenesis); err == nil { var g Genesis if err := json.Unmarshal(bs, &g); err == nil { return &g @@ -373,7 +373,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 := gob.Decode(b, g); err == nil { return g } return nil diff --git a/types/genesis_test.go b/types/genesis_test.go index d464648e3..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.ToString(chainID)) + fmt.Println("chain_id: ", base58.Encode(chainID)) } func TestGenesisBytes(t *testing.T) { diff --git a/types/logging.go b/types/logging.go index 329b24c40..a0a479876 100644 --- a/types/logging.go +++ b/types/logging.go @@ -7,7 +7,8 @@ package types import ( "fmt" - "github.com/aergoio/aergo/v2/internal/enc" + + "github.com/aergoio/aergo/v2/internal/enc/base58" "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", base58.Encode(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", base58.Encode(t.GetHash())).Str("account", base58.Encode(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 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 7c1bfb964..88383416d 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/aergoio/aergo/v2/internal/enc/base58" "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", base58.Encode(t)) } func BenchmarkLogMemAllocationWrapper(b *testing.B) { diff --git a/types/p2p_test.go b/types/p2p_test.go index ef88473af..ebd5d3106 100644 --- a/types/p2p_test.go +++ b/types/p2p_test.go @@ -6,23 +6,23 @@ package types import ( - "encoding/hex" "fmt" "testing" - "github.com/aergoio/aergo/v2/internal/enc" - "github.com/golang/protobuf/proto" + "github.com/aergoio/aergo/v2/internal/enc/base58" + "github.com/aergoio/aergo/v2/internal/enc/hex" + "github.com/aergoio/aergo/v2/internal/enc/proto" "github.com/stretchr/testify/assert" ) func TestUnmarshalSize(t *testing.T) { - var dummyTxHash, _ = enc.ToBytes("4H4zAkAyRV253K5SNBJtBxqUgHEbZcXbWFFc6cmQHY45") - fmt.Println("Hash: ", hex.EncodeToString(dummyTxHash)) + var dummyTxHash, _ = base58.Decode("4H4zAkAyRV253K5SNBJtBxqUgHEbZcXbWFFc6cmQHY45") + fmt.Println("Hash: ", hex.Encode(dummyTxHash)) 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,10 +32,10 @@ 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.EncodeToString(actual)) + fmt.Println("Hex: ", hex.Encode(actual)) assert.Equal(t, expectedLen, len(actual)) // 100 hashes @@ -45,10 +45,10 @@ 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.EncodeToString(actual[0:40])) + fmt.Println("Hex: ", hex.Encode(actual[0:40])) assert.Equal(t, expectedLen, len(actual)) // 1000 hashes @@ -58,10 +58,10 @@ 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.EncodeToString(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 0b25b1d8d..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.ToString(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.ToString(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.ToString(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.ToString(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.ToString(m.ProducerID)).Uint64(LogBlkNo, m.BlockNo).Str(LogBlkHash, enc.ToString(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.ToString(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.ToString(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.ToString(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.ToString(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.ToString(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.ToString(m.BestBlockHash)) + e.Str("best_hash", base58.Encode(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, 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 524243b16..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.ToString(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.ToString(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.ToString(ev.TxHash)) + b.WriteString(base58.Encode(ev.TxHash)) b.WriteString(`","EventIdx":`) b.WriteString(fmt.Sprintf("%d", ev.EventIdx)) b.WriteString(`,"BlockHash":"`) - b.WriteString(enc.ToString(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 c33577631..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.ToString(id[:]) + return base58.Encode(id[:]) } // Bytes make a byte slice from id diff --git a/types/transaction.go b/types/transaction.go index 61fac049f..ae88e8789 100644 --- a/types/transaction.go +++ b/types/transaction.go @@ -8,8 +8,8 @@ import ( "strings" "github.com/aergoio/aergo/v2/fee" - "github.com/golang/protobuf/proto" - "github.com/mr-tron/base58/base58" + "github.com/aergoio/aergo/v2/internal/enc/base58" + "github.com/aergoio/aergo/v2/internal/enc/proto" ) //governance type transaction which has aergo.system in recipient