refactor(*): update Hash/Address related code in executor and ledger

This commit is contained in:
zhourong 2020-10-21 19:38:51 +08:00
parent cb74880701
commit 52e758e5dc
12 changed files with 120 additions and 107 deletions

View File

@ -20,8 +20,8 @@ func TestAppchainManager_Appchain(t *testing.T) {
mockCtl := gomock.NewController(t)
mockStub := mock_stub.NewMockStub(mockCtl)
addr0 := types.Bytes2Address([]byte{0}).String()
addr1 := types.Bytes2Address([]byte{1}).String()
addr0 := types.NewAddress([]byte{0}).String()
addr1 := types.NewAddress([]byte{1}).String()
chain := &appchainMgr.Appchain{
ID: addr0,
@ -62,7 +62,7 @@ func TestAppchainManager_Appchains(t *testing.T) {
var chains []*appchainMgr.Appchain
var chainsData [][]byte
for i := 0; i < 2; i++ {
addr := types.Bytes2Address([]byte{byte(i)}).String()
addr := types.NewAddress([]byte{byte(i)}).String()
chain := &appchainMgr.Appchain{
ID: addr,
@ -109,7 +109,7 @@ func TestInterchainManager_Register(t *testing.T) {
mockCtl := gomock.NewController(t)
mockStub := mock_stub.NewMockStub(mockCtl)
addr := types.Bytes2Address([]byte{0}).String()
addr := types.NewAddress([]byte{0}).String()
mockStub.EXPECT().Caller().Return(addr).AnyTimes()
mockStub.EXPECT().Set(gomock.Any(), gomock.Any()).AnyTimes()
o1 := mockStub.EXPECT().Get(appchainMgr.PREFIX+addr).Return(false, nil)
@ -164,7 +164,7 @@ func TestInterchainManager_Interchain(t *testing.T) {
mockCtl := gomock.NewController(t)
mockStub := mock_stub.NewMockStub(mockCtl)
addr := types.Bytes2Address([]byte{0}).String()
addr := types.NewAddress([]byte{0}).String()
mockStub.EXPECT().Caller().Return(addr).AnyTimes()
mockStub.EXPECT().Set(gomock.Any(), gomock.Any()).AnyTimes()
o1 := mockStub.EXPECT().Get(appchainMgr.PREFIX+addr).Return(false, nil)
@ -197,7 +197,7 @@ func TestInterchainManager_GetInterchain(t *testing.T) {
mockCtl := gomock.NewController(t)
mockStub := mock_stub.NewMockStub(mockCtl)
addr := types.Bytes2Address([]byte{0}).String()
addr := types.NewAddress([]byte{0}).String()
mockStub.EXPECT().Set(gomock.Any(), gomock.Any()).AnyTimes()
o1 := mockStub.EXPECT().Get(appchainMgr.PREFIX+addr).Return(false, nil)
@ -229,8 +229,8 @@ func TestInterchainManager_HandleIBTP(t *testing.T) {
mockCtl := gomock.NewController(t)
mockStub := mock_stub.NewMockStub(mockCtl)
from := types.Bytes2Address([]byte{0}).String()
to := types.Bytes2Address([]byte{1}).String()
from := types.NewAddress([]byte{0}).String()
to := types.NewAddress([]byte{1}).String()
mockStub.EXPECT().Set(gomock.Any(), gomock.Any()).AnyTimes()
f1 := mockStub.EXPECT().Get(appchainMgr.PREFIX+from).Return(false, nil)
@ -362,8 +362,8 @@ func TestInterchainManager_GetIBTPByID(t *testing.T) {
mockCtl := gomock.NewController(t)
mockStub := mock_stub.NewMockStub(mockCtl)
from := types.Bytes2Address([]byte{0}).String()
to := types.Bytes2Address([]byte{1}).String()
from := types.NewAddress([]byte{0}).String()
to := types.NewAddress([]byte{1}).String()
validID := fmt.Sprintf("%s-%s-1", from, to)
@ -394,10 +394,10 @@ func TestRole_GetRole(t *testing.T) {
mockCtl := gomock.NewController(t)
mockStub := mock_stub.NewMockStub(mockCtl)
addrs := []string{types.Bytes2Address([]byte{0}).String(), types.Bytes2Address([]byte{1}).String()}
addrs := []string{types.NewAddress([]byte{0}).String(), types.NewAddress([]byte{1}).String()}
mockStub.EXPECT().GetObject(adminRolesKey, gomock.Any()).SetArg(1, addrs).AnyTimes()
mockStub.EXPECT().Caller().Return(types.Bytes2Address([]byte{0}).String())
mockStub.EXPECT().Caller().Return(types.NewAddress([]byte{0}).String())
im := &Role{mockStub}
@ -405,7 +405,7 @@ func TestRole_GetRole(t *testing.T) {
assert.True(t, res.Ok)
assert.Equal(t, "admin", string(res.Result))
mockStub.EXPECT().Caller().Return(types.Bytes2Address([]byte{2}).String()).AnyTimes()
mockStub.EXPECT().Caller().Return(types.NewAddress([]byte{2}).String()).AnyTimes()
mockStub.EXPECT().CrossInvoke(gomock.Any(), gomock.Any(), gomock.Any()).Return(boltvm.Error(""))
res = im.GetRole()
@ -423,7 +423,7 @@ func TestRole_IsAdmin(t *testing.T) {
mockCtl := gomock.NewController(t)
mockStub := mock_stub.NewMockStub(mockCtl)
addrs := []string{types.Bytes2Address([]byte{0}).String(), types.Bytes2Address([]byte{1}).String()}
addrs := []string{types.NewAddress([]byte{0}).String(), types.NewAddress([]byte{1}).String()}
mockStub.EXPECT().GetObject(adminRolesKey, gomock.Any()).SetArg(1, addrs).AnyTimes()
@ -433,7 +433,7 @@ func TestRole_IsAdmin(t *testing.T) {
assert.True(t, res.Ok)
assert.Equal(t, "true", string(res.Result))
res = im.IsAdmin(types.Bytes2Address([]byte{2}).String())
res = im.IsAdmin(types.NewAddress([]byte{2}).String())
assert.True(t, res.Ok)
assert.Equal(t, "false", string(res.Result))
}
@ -442,7 +442,7 @@ func TestRole_GetAdminRoles(t *testing.T) {
mockCtl := gomock.NewController(t)
mockStub := mock_stub.NewMockStub(mockCtl)
addrs := []string{types.Bytes2Address([]byte{0}).String(), types.Bytes2Address([]byte{1}).String()}
addrs := []string{types.NewAddress([]byte{0}).String(), types.NewAddress([]byte{1}).String()}
mockStub.EXPECT().GetObject(adminRolesKey, gomock.Any()).SetArg(1, addrs).AnyTimes()
@ -464,7 +464,7 @@ func TestRole_SetAdminRoles(t *testing.T) {
mockCtl := gomock.NewController(t)
mockStub := mock_stub.NewMockStub(mockCtl)
addrs := []string{types.Bytes2Address([]byte{0}).String(), types.Bytes2Address([]byte{1}).String()}
addrs := []string{types.NewAddress([]byte{0}).String(), types.NewAddress([]byte{1}).String()}
mockStub.EXPECT().SetObject(adminRolesKey, addrs).AnyTimes()
im := &Role{mockStub}
@ -480,8 +480,8 @@ func TestRuleManager_RegisterRule(t *testing.T) {
mockCtl := gomock.NewController(t)
mockStub := mock_stub.NewMockStub(mockCtl)
id0 := types.Bytes2Address([]byte{0}).String()
id1 := types.Bytes2Address([]byte{1}).String()
id0 := types.NewAddress([]byte{0}).String()
id1 := types.NewAddress([]byte{1}).String()
mockStub.EXPECT().CrossInvoke(constant.AppchainMgrContractAddr.String(), "GetAppchain", pb.String(id0)).Return(boltvm.Success(nil))
mockStub.EXPECT().CrossInvoke(constant.AppchainMgrContractAddr.String(), "GetAppchain", pb.String(id1)).Return(boltvm.Error(""))
@ -489,7 +489,7 @@ func TestRuleManager_RegisterRule(t *testing.T) {
im := &RuleManager{mockStub}
addr := types.Bytes2Address([]byte{2}).String()
addr := types.NewAddress([]byte{2}).String()
res := im.RegisterRule(id0, addr)
assert.True(t, res.Ok)
@ -502,8 +502,8 @@ func TestRuleManager_GetRuleAddress(t *testing.T) {
mockCtl := gomock.NewController(t)
mockStub := mock_stub.NewMockStub(mockCtl)
id0 := types.Bytes2Address([]byte{0}).String()
id1 := types.Bytes2Address([]byte{1}).String()
id0 := types.NewAddress([]byte{0}).String()
id1 := types.NewAddress([]byte{1}).String()
rule := Rule{
Address: "123",
Status: 1,
@ -531,8 +531,8 @@ func TestRuleManager_Audit(t *testing.T) {
mockCtl := gomock.NewController(t)
mockStub := mock_stub.NewMockStub(mockCtl)
id0 := types.Bytes2Address([]byte{0}).String()
id1 := types.Bytes2Address([]byte{1}).String()
id0 := types.NewAddress([]byte{0}).String()
id1 := types.NewAddress([]byte{1}).String()
rule := Rule{
Address: "123",
Status: 1,
@ -591,7 +591,7 @@ func TestTransactionManager_Begin(t *testing.T) {
mockCtl := gomock.NewController(t)
mockStub := mock_stub.NewMockStub(mockCtl)
id := types.Bytes2Hash([]byte{0}).String()
id := types.NewHash([]byte{0}).String()
mockStub.EXPECT().AddObject(fmt.Sprintf("%s-%s", PREFIX, id), pb.TransactionStatus_BEGIN)
im := &TransactionManager{mockStub}
@ -778,8 +778,8 @@ func TestAssetExchange_Init(t *testing.T) {
mockCtl := gomock.NewController(t)
mockStub := mock_stub.NewMockStub(mockCtl)
from := types.Bytes2Address([]byte{0}).String()
to := types.Bytes2Address([]byte{1}).String()
from := types.NewAddress([]byte{0}).String()
to := types.NewAddress([]byte{1}).String()
ae := &AssetExchange{mockStub}
@ -827,8 +827,8 @@ func TestAssetExchange_Redeem(t *testing.T) {
mockCtl := gomock.NewController(t)
mockStub := mock_stub.NewMockStub(mockCtl)
from := types.Bytes2Address([]byte{0}).String()
to := types.Bytes2Address([]byte{1}).String()
from := types.NewAddress([]byte{0}).String()
to := types.NewAddress([]byte{1}).String()
ae := &AssetExchange{mockStub}
@ -880,8 +880,8 @@ func TestAssetExchange_Refund(t *testing.T) {
mockCtl := gomock.NewController(t)
mockStub := mock_stub.NewMockStub(mockCtl)
from := types.Bytes2Address([]byte{0}).String()
to := types.Bytes2Address([]byte{1}).String()
from := types.NewAddress([]byte{0}).String()
to := types.NewAddress([]byte{1}).String()
ae := &AssetExchange{mockStub}
@ -943,8 +943,8 @@ func TestAssetExchange_GetStatus(t *testing.T) {
AssetOnDst: 100,
}
from := types.Bytes2Address([]byte{0}).String()
to := types.Bytes2Address([]byte{1}).String()
from := types.NewAddress([]byte{0}).String()
to := types.NewAddress([]byte{1}).String()
aer := AssetExchangeRecord{
Chain0: from,
Chain1: to,

View File

@ -389,7 +389,7 @@ func (x *InterchainManager) checkUnionIBTP(app *appchainMgr.Appchain, ibtp *pb.I
return fmt.Errorf("wrong validator: %s", v)
}
delete(m, v)
addr := types.String2Address(v)
addr := types.NewAddressByStr(v)
ok, _ := asym.Verify(crypto.Secp256k1, sign, hash[:], *addr)
if ok {
counter++

View File

@ -86,7 +86,7 @@ func (exec *BlockExecutor) Start() error {
exec.logger.WithFields(logrus.Fields{
"height": exec.currentHeight,
"hash": exec.currentBlockHash.ShortString(),
"hash": exec.currentBlockHash.String(),
}).Infof("BlockExecutor started")
return nil
@ -209,7 +209,7 @@ func (exec *BlockExecutor) persistData() {
exec.postBlockEvent(data.Block, data.InterchainMeta)
exec.logger.WithFields(logrus.Fields{
"height": data.Block.BlockHeader.Number,
"hash": data.Block.BlockHash.ShortString(),
"hash": data.Block.BlockHash.String(),
"count": len(data.Block.Transactions),
"elapse": time.Since(now),
}).Info("Persisted block")

View File

@ -42,7 +42,7 @@ func TestNew(t *testing.T) {
// mock data for ledger
chainMeta := &pb.ChainMeta{
Height: 1,
BlockHash: types.String2Hash(from),
BlockHash: *types.NewHashByStr(from),
}
mockLedger.EXPECT().GetChainMeta().Return(chainMeta).AnyTimes()
@ -71,7 +71,7 @@ func TestBlockExecutor_ExecuteBlock(t *testing.T) {
// mock data for ledger
chainMeta := &pb.ChainMeta{
Height: 1,
BlockHash: types.String2Hash(from),
BlockHash: *types.NewHashByStr(from),
}
evs := make([]*pb.Event, 0)
@ -80,7 +80,7 @@ func TestBlockExecutor_ExecuteBlock(t *testing.T) {
data, err := json.Marshal(m)
assert.Nil(t, err)
ev := &pb.Event{
TxHash: types.String2Hash(from),
TxHash: *types.NewHashByStr(from),
Data: data,
Interchain: true,
}
@ -132,7 +132,8 @@ func TestBlockExecutor_ExecuteBlock(t *testing.T) {
// set signature for txs
for _, tx := range txs {
tx.From, err = pubKey.Address()
addr, err := pubKey.Address()
tx.From = *addr
assert.Nil(t, err)
sig, err := privKey.Sign(tx.SignHash().Bytes())
assert.Nil(t, err)
@ -140,7 +141,7 @@ func TestBlockExecutor_ExecuteBlock(t *testing.T) {
}
// set invalid signature tx
invalidTx := mockTx(nil)
invalidTx.From = types.String2Address(from)
invalidTx.From = *types.NewAddressByStr(from)
invalidTx.Signature = []byte("invalid")
txs = append(txs, invalidTx)
@ -174,7 +175,7 @@ func TestBlockExecutor_ApplyReadonlyTransactions(t *testing.T) {
// mock data for ledger
chainMeta := &pb.ChainMeta{
Height: 1,
BlockHash: types.String2Hash(from),
BlockHash: *types.NewHashByStr(from),
}
privKey, err := asym.GenerateKeyPair(crypto.Secp256k1)
@ -184,7 +185,7 @@ func TestBlockExecutor_ApplyReadonlyTransactions(t *testing.T) {
assert.Nil(t, err)
id := fmt.Sprintf("%s-%s-%d", addr.String(), to, 1)
hash := types.Hash{1}
hash := types.NewHash([]byte{1})
val, err := json.Marshal(hash)
assert.Nil(t, err)
@ -203,7 +204,7 @@ func TestBlockExecutor_ApplyReadonlyTransactions(t *testing.T) {
// mock data for block
var txs []*pb.Transaction
tx, err := genBVMContractTransaction(privKey, 1, constant.InterchainContractAddr.Address(), "GetIBTPByID", pb.String(id))
tx, err := genBVMContractTransaction(privKey, 1, *constant.InterchainContractAddr.Address(), "GetIBTPByID", pb.String(id))
assert.Nil(t, err)
txs = append(txs, tx)
@ -237,9 +238,10 @@ func mockBlock(blockNumber uint64, txs []*pb.Transaction) *pb.Block {
}
func mockTx(data *pb.TransactionData) *pb.Transaction {
content, _ := data.Marshal()
return &pb.Transaction{
Data: data,
Nonce: uint64(rand.Int63()),
Payload: content,
Nonce: uint64(rand.Int63()),
}
}
@ -305,20 +307,25 @@ func mockTransferTx(t *testing.T) *pb.Transaction {
privKey, from := loadAdminKey(t)
to := randAddress(t)
transactionData := &pb.TransactionData{
Type: pb.TransactionData_NORMAL,
Amount: 1,
}
data, err := transactionData.Marshal()
require.Nil(t, err)
tx := &pb.Transaction{
From: from,
To: to,
Timestamp: time.Now().UnixNano(),
Data: &pb.TransactionData{
Type: pb.TransactionData_NORMAL,
Amount: 1,
},
Nonce: uint64(rand.Int63()),
Payload: data,
Nonce: uint64(rand.Int63()),
}
err := tx.Sign(privKey)
err = tx.Sign(privKey)
require.Nil(t, err)
tx.TransactionHash = tx.Hash()
tx.TransactionHash = *tx.Hash()
return tx
}
@ -330,7 +337,7 @@ func loadAdminKey(t *testing.T) (crypto.PrivateKey, types.Address) {
from, err := privKey.PublicKey().Address()
require.Nil(t, err)
return privKey, from
return privKey, *from
}
func randAddress(t *testing.T) types.Address {
@ -339,7 +346,7 @@ func randAddress(t *testing.T) types.Address {
address, err := privKey.PublicKey().Address()
require.Nil(t, err)
return address
return *address
}
func genBVMContractTransaction(privateKey crypto.PrivateKey, nonce uint64, address types.Address, method string, args ...*pb.Arg) (*pb.Transaction, error) {
@ -372,10 +379,15 @@ func genContractTransaction(vmType pb.TransactionData_VMType, privateKey crypto.
Payload: data,
}
pld, err := td.Marshal()
if err != nil {
return nil, err
}
tx := &pb.Transaction{
From: from,
From: *from,
To: address,
Data: td,
Payload: pld,
Timestamp: time.Now().UnixNano(),
Nonce: nonce,
}
@ -384,7 +396,7 @@ func genContractTransaction(vmType pb.TransactionData_VMType, privateKey crypto.
return nil, fmt.Errorf("tx sign: %w", err)
}
tx.TransactionHash = tx.Hash()
tx.TransactionHash = *tx.Hash()
return tx, nil
}
@ -448,7 +460,7 @@ BcNwjTDCxyxLNjFKQfMAc6sY6iJs+Ma59WZyC/4uhjE=
return &repo.Repo{
Key: &repo.Key{
PrivKey: privKey,
Address: address.Hex(),
Address: address.String(),
},
}
}

View File

@ -57,9 +57,9 @@ func (exec *BlockExecutor) processExecuteEvent(block *pb.Block) *ledger.BlockDat
block.BlockHash = *block.Hash()
exec.logger.WithFields(logrus.Fields{
"tx_root": block.BlockHeader.TxRoot.ShortString(),
"receipt_root": block.BlockHeader.ReceiptRoot.ShortString(),
"state_root": block.BlockHeader.StateRoot.ShortString(),
"tx_root": block.BlockHeader.TxRoot.String(),
"receipt_root": block.BlockHeader.ReceiptRoot.String(),
"state_root": block.BlockHeader.StateRoot.String(),
}).Debug("block meta")
calcBlockSize.Observe(float64(block.Size()))
executeBlockDuration.Observe(float64(time.Since(current)) / float64(time.Second))
@ -223,7 +223,7 @@ func (exec *BlockExecutor) applyTx(index int, tx *pb.Transaction, opt *agency.Tx
receipt.Ret = ret
}
events := exec.ledger.Events(tx.TransactionHash.Hex())
events := exec.ledger.Events(tx.TransactionHash.String())
if len(events) != 0 {
receipt.Events = events
for _, ev := range events {
@ -302,7 +302,7 @@ func (exec *BlockExecutor) transfer(from, to types.Address, value uint64) error
fv := exec.ledger.GetBalance(from)
if fv < value {
return fmt.Errorf("not sufficient funds for %s", from.Hex())
return fmt.Errorf("not sufficient funds for %s", from.String())
}
tv := exec.ledger.GetBalance(to)
@ -341,7 +341,7 @@ func calcMerkleRoot(contents []merkletree.Content) (types.Hash, error) {
return types.Hash{}, err
}
return *types.Bytes2Hash(tree.MerkleRoot()), nil
return *types.NewHash(tree.MerkleRoot()), nil
}
func (exec *BlockExecutor) getContracts(opt *agency.TxOpt) map[string]agency.Contract {

View File

@ -255,7 +255,7 @@ func (o *Account) getStateJournalAndComputeHash() map[string][]byte {
dirtyStateData = append(dirtyStateData, dirtyVal.([]byte)...)
}
hash := sha256.Sum256(dirtyStateData)
o.dirtyStateHash = *types.Bytes2Hash(hash[:])
o.dirtyStateHash = *types.NewHash(hash[:])
return prevStates
}

View File

@ -27,7 +27,7 @@ func TestAccount_GetState(t *testing.T) {
assert.Nil(t, err)
h := hexutil.Encode(bytesutil.LeftPadBytes([]byte{11}, 20))
addr := types.String2Address(h)
addr := types.NewAddressByStr(h)
account := newAccount(ledger.ldb, ledger.accountCache, *addr)
account.SetState([]byte("a"), []byte("b"))

View File

@ -70,7 +70,7 @@ func (l *ChainLedger) GetBlockSign(height uint64) ([]byte, error) {
// GetBlockByHash get the block using block hash
func (l *ChainLedger) GetBlockByHash(hash types.Hash) (*pb.Block, error) {
data := l.blockchainStore.Get(compositeKey(blockHashKey, hash.Hex()))
data := l.blockchainStore.Get(compositeKey(blockHashKey, hash.String()))
if data == nil {
return nil, storage.ErrorNotFound
}
@ -85,7 +85,7 @@ func (l *ChainLedger) GetBlockByHash(hash types.Hash) (*pb.Block, error) {
// GetTransaction get the transaction using transaction hash
func (l *ChainLedger) GetTransaction(hash types.Hash) (*pb.Transaction, error) {
v := l.blockchainStore.Get(compositeKey(transactionKey, hash.Hex()))
v := l.blockchainStore.Get(compositeKey(transactionKey, hash.String()))
if v == nil {
return nil, storage.ErrorNotFound
}
@ -112,7 +112,7 @@ func (l *ChainLedger) GetTransactionCount(height uint64) (uint64, error) {
// GetTransactionMeta get the transaction meta data
func (l *ChainLedger) GetTransactionMeta(hash types.Hash) (*pb.TransactionMeta, error) {
data := l.blockchainStore.Get(compositeKey(transactionMetaKey, hash.Hex()))
data := l.blockchainStore.Get(compositeKey(transactionMetaKey, hash.String()))
if data == nil {
return nil, storage.ErrorNotFound
}
@ -127,7 +127,7 @@ func (l *ChainLedger) GetTransactionMeta(hash types.Hash) (*pb.TransactionMeta,
// GetReceipt get the transaction receipt
func (l *ChainLedger) GetReceipt(hash types.Hash) (*pb.Receipt, error) {
data := l.blockchainStore.Get(compositeKey(receiptKey, hash.Hex()))
data := l.blockchainStore.Get(compositeKey(receiptKey, hash.String()))
if data == nil {
return nil, storage.ErrorNotFound
}
@ -233,7 +233,7 @@ func (l *ChainLedger) persistReceipts(batcher storage.Batch, receipts []*pb.Rece
return err
}
batcher.Put(compositeKey(receiptKey, receipt.TxHash.Hex()), data)
batcher.Put(compositeKey(receiptKey, receipt.TxHash.String()), data)
}
return nil
@ -246,7 +246,7 @@ func (l *ChainLedger) persistTransactions(batcher storage.Batch, block *pb.Block
return err
}
batcher.Put(compositeKey(transactionKey, tx.TransactionHash.Hex()), body)
batcher.Put(compositeKey(transactionKey, tx.TransactionHash.String()), body)
meta := &pb.TransactionMeta{
BlockHeight: block.BlockHeader.Number,
@ -259,7 +259,7 @@ func (l *ChainLedger) persistTransactions(batcher storage.Batch, block *pb.Block
return fmt.Errorf("marshal tx meta error: %s", err)
}
batcher.Put(compositeKey(transactionMetaKey, tx.TransactionHash.Hex()), bs)
batcher.Put(compositeKey(transactionMetaKey, tx.TransactionHash.String()), bs)
}
return nil
@ -301,7 +301,7 @@ func (l *ChainLedger) persistBlock(batcher storage.Batch, block *pb.Block) error
batcher.Put(compositeKey(blockTxSetKey, height), data)
hash := block.BlockHash.Hex()
hash := block.BlockHash.String()
batcher.Put(compositeKey(blockHashKey, hash), []byte(fmt.Sprintf("%d", height)))
return nil
@ -340,13 +340,13 @@ func (l *ChainLedger) removeChainDataOnBlock(batch storage.Batch, height uint64)
}
batch.Delete(compositeKey(blockKey, height))
batch.Delete(compositeKey(blockHashKey, block.BlockHash.Hex()))
batch.Delete(compositeKey(blockHashKey, block.BlockHash.String()))
batch.Delete(compositeKey(interchainMetaKey, height))
for _, tx := range block.Transactions {
batch.Delete(compositeKey(transactionKey, tx.TransactionHash.Hex()))
batch.Delete(compositeKey(transactionMetaKey, tx.TransactionHash.Hex()))
batch.Delete(compositeKey(receiptKey, tx.TransactionHash.Hex()))
batch.Delete(compositeKey(transactionKey, tx.TransactionHash.String()))
batch.Delete(compositeKey(transactionMetaKey, tx.TransactionHash.String()))
batch.Delete(compositeKey(receiptKey, tx.TransactionHash.String()))
}
return getInterchainTxCount(interchainMeta), nil

View File

@ -11,13 +11,13 @@ import (
)
var (
roleAddr = types.Bytes2Address(bytesutil.LeftPadBytes([]byte{13}, 20))
roleAddr = types.NewAddress(bytesutil.LeftPadBytes([]byte{13}, 20))
)
// Initialize initialize block
func Initialize(genesis *repo.Genesis, lg ledger.Ledger) error {
for _, addr := range genesis.Addresses {
lg.SetBalance(types.String2Address(addr), 100000000)
lg.SetBalance(*types.NewAddressByStr(addr), 100000000)
}
body, err := json.Marshal(genesis.Addresses)
@ -25,7 +25,7 @@ func Initialize(genesis *repo.Genesis, lg ledger.Ledger) error {
return err
}
lg.SetState(roleAddr, []byte("admin-roles"), body)
lg.SetState(*roleAddr, []byte("admin-roles"), body)
accounts, journal := lg.FlushDirtyDataAndComputeJournal()
block := &pb.Block{
@ -34,7 +34,7 @@ func Initialize(genesis *repo.Genesis, lg ledger.Ledger) error {
StateRoot: journal.ChangedHash,
},
}
block.BlockHash = block.Hash()
block.BlockHash = *block.Hash()
blockData := &ledger.BlockData{
Block: block,
Receipts: nil,

View File

@ -163,7 +163,7 @@ func (l *ChainLedger) RemoveJournalsBeforeBlock(height uint64) error {
// AddEvent add ledger event
func (l *ChainLedger) AddEvent(event *pb.Event) {
var events []*pb.Event
hash := event.TxHash.Hex()
hash := event.TxHash.String()
value, ok := l.events.Load(hash)
if ok {
events = value.([]*pb.Event)

View File

@ -118,9 +118,9 @@ func TestChainLedger_PersistBlockData(t *testing.T) {
ledger, _ := initLedger(t, "")
// create an account
account := types.Bytes2Address(bytesutil.LeftPadBytes([]byte{100}, 20))
account := types.NewAddress(bytesutil.LeftPadBytes([]byte{100}, 20))
ledger.SetState(account, []byte("a"), []byte("b"))
ledger.SetState(*account, []byte("a"), []byte("b"))
accounts, journal := ledger.FlushDirtyDataAndComputeJournal()
ledger.PersistBlockData(genBlockData(1, accounts, journal))
}
@ -129,20 +129,20 @@ func TestChainLedger_Commit(t *testing.T) {
ledger, repoRoot := initLedger(t, "")
// create an account
account := types.Bytes2Address(bytesutil.LeftPadBytes([]byte{100}, 20))
account := *types.NewAddress(bytesutil.LeftPadBytes([]byte{100}, 20))
ledger.SetState(account, []byte("a"), []byte("b"))
accounts, journal := ledger.FlushDirtyDataAndComputeJournal()
err := ledger.Commit(1, accounts, journal)
assert.Nil(t, err)
assert.Equal(t, uint64(1), ledger.Version())
assert.Equal(t, "0xA1a6d35708Fa6Cf804B6cF9479F3a55d9A87FbFB83c55a64685AeaBdBa6116B1", journal.ChangedHash.Hex())
assert.Equal(t, "0xA1a6d35708Fa6Cf804B6cF9479F3a55d9A87FbFB83c55a64685AeaBdBa6116B1", journal.ChangedHash.String())
accounts, journal = ledger.FlushDirtyDataAndComputeJournal()
err = ledger.Commit(2, accounts, journal)
assert.Nil(t, err)
assert.Equal(t, uint64(2), ledger.Version())
assert.Equal(t, "0xF09F0198C06D549316D4ee7C497C9eaeF9D24f5b1075e7bCEF3D0a82DfA742cF", journal.ChangedHash.Hex())
assert.Equal(t, "0xF09F0198C06D549316D4ee7C497C9eaeF9D24f5b1075e7bCEF3D0a82DfA742cF", journal.ChangedHash.String())
ledger.SetState(account, []byte("a"), []byte("3"))
ledger.SetState(account, []byte("a"), []byte("2"))
@ -150,14 +150,14 @@ func TestChainLedger_Commit(t *testing.T) {
err = ledger.Commit(3, accounts, journal)
assert.Nil(t, err)
assert.Equal(t, uint64(3), ledger.Version())
assert.Equal(t, "0xe9FC370DD36C9BD5f67cCfbc031C909F53A3d8bC7084C01362c55f2D42bA841c", journal.ChangedHash.Hex())
assert.Equal(t, "0xe9FC370DD36C9BD5f67cCfbc031C909F53A3d8bC7084C01362c55f2D42bA841c", journal.ChangedHash.String())
ledger.SetBalance(account, 100)
accounts, journal = ledger.FlushDirtyDataAndComputeJournal()
err = ledger.Commit(4, accounts, journal)
assert.Nil(t, err)
assert.Equal(t, uint64(4), ledger.Version())
assert.Equal(t, "0xC179056204BA33eD6CFC0bfE94ca03319BEb522fd7B0773A589899817B49ec08", journal.ChangedHash.Hex())
assert.Equal(t, "0xC179056204BA33eD6CFC0bfE94ca03319BEb522fd7B0773A589899817B49ec08", journal.ChangedHash.String())
code := bytesutil.RightPadBytes([]byte{100}, 100)
ledger.SetCode(account, code)
@ -214,8 +214,8 @@ func TestChainLedger_Rollback(t *testing.T) {
ledger, repoRoot := initLedger(t, "")
// create an addr0
addr0 := types.Bytes2Address(bytesutil.LeftPadBytes([]byte{100}, 20))
addr1 := types.Bytes2Address(bytesutil.LeftPadBytes([]byte{101}, 20))
addr0 := *types.NewAddress(bytesutil.LeftPadBytes([]byte{100}, 20))
addr1 := *types.NewAddress(bytesutil.LeftPadBytes([]byte{101}, 20))
hash0 := types.Hash{}
assert.Equal(t, hash0, ledger.prevJnlHash)
@ -391,7 +391,7 @@ func TestChainLedger_RemoveJournalsBeforeBlock(t *testing.T) {
func TestChainLedger_QueryByPrefix(t *testing.T) {
ledger, _ := initLedger(t, "")
addr := types.Bytes2Address(bytesutil.LeftPadBytes([]byte{1}, 20))
addr := *types.NewAddress(bytesutil.LeftPadBytes([]byte{1}, 20))
key0 := []byte{100, 100}
key1 := []byte{100, 101}
key2 := []byte{100, 102}
@ -426,7 +426,7 @@ func TestChainLedger_QueryByPrefix(t *testing.T) {
func TestChainLedger_GetAccount(t *testing.T) {
ledger, _ := initLedger(t, "")
addr := types.Bytes2Address(bytesutil.LeftPadBytes([]byte{1}, 20))
addr := *types.NewAddress(bytesutil.LeftPadBytes([]byte{1}, 20))
code := bytesutil.LeftPadBytes([]byte{1}, 120)
key0 := []byte{100, 100}
key1 := []byte{100, 101}
@ -484,7 +484,7 @@ func TestChainLedger_GetAccount(t *testing.T) {
func TestChainLedger_GetCode(t *testing.T) {
ledger, _ := initLedger(t, "")
addr := types.Bytes2Address(bytesutil.LeftPadBytes([]byte{1}, 20))
addr := *types.NewAddress(bytesutil.LeftPadBytes([]byte{1}, 20))
code := bytesutil.LeftPadBytes([]byte{10}, 120)
code0 := ledger.GetCode(addr)
@ -513,7 +513,7 @@ func TestChainLedger_GetCode(t *testing.T) {
func TestChainLedger_AddAccountsToCache(t *testing.T) {
ledger, _ := initLedger(t, "")
addr := types.Bytes2Address(bytesutil.LeftPadBytes([]byte{1}, 20))
addr := *types.NewAddress(bytesutil.LeftPadBytes([]byte{1}, 20))
key := []byte{1}
val := []byte{2}
code := bytesutil.RightPadBytes([]byte{1, 2, 3, 4}, 100)
@ -530,7 +530,8 @@ func TestChainLedger_AddAccountsToCache(t *testing.T) {
assert.True(t, ok)
assert.Equal(t, uint64(100), innerAccount.Balance)
assert.Equal(t, uint64(1), innerAccount.Nonce)
assert.Equal(t, types.Hash(sha256.Sum256(code)).Bytes(), innerAccount.CodeHash)
codeHash := sha256.Sum256(code)
assert.Equal(t, types.NewHash(codeHash[:]).Bytes(), innerAccount.CodeHash)
val1, ok := ledger.accountCache.getState(addr, string(key))
assert.True(t, ok)
@ -573,7 +574,7 @@ func TestChainLedger_GetInterchainMeta(t *testing.T) {
ledger, _ := initLedger(t, "")
// create an account
account := types.Bytes2Address(bytesutil.LeftPadBytes([]byte{100}, 20))
account := *types.NewAddress(bytesutil.LeftPadBytes([]byte{100}, 20))
ledger.SetState(account, []byte("a"), []byte("b"))
accounts, journal := ledger.FlushDirtyDataAndComputeJournal()
@ -593,7 +594,7 @@ func TestChainLedger_GetInterchainMeta(t *testing.T) {
L2Roots: make([]types.Hash, 0),
}
meta.Counter["a"] = &pb.Uint64Slice{}
meta.L2Roots = append(meta.L2Roots, [32]byte{})
meta.L2Roots = append(meta.L2Roots, *types.NewHash([]byte{}))
batch := ledger.blockchainStore.NewBatch()
err = ledger.persistInterChainMeta(batch, meta, 2)
require.Nil(t, err)
@ -609,7 +610,7 @@ func TestChainLedger_GetInterchainMeta(t *testing.T) {
func TestChainLedger_AddState(t *testing.T) {
ledger, _ := initLedger(t, "")
account := types.Bytes2Address(bytesutil.LeftPadBytes([]byte{100}, 20))
account := *types.NewAddress(bytesutil.LeftPadBytes([]byte{100}, 20))
key0 := "100"
value0 := []byte{100}
ledger.AddState(account, []byte(key0), value0)
@ -644,8 +645,8 @@ func TestChainLedger_AddState(t *testing.T) {
func TestChainLedger_AddEvent(t *testing.T) {
ledger, _ := initLedger(t, "")
hash0 := types.Hash{1}
hash1 := types.Hash{2}
hash0 := *types.NewHash([]byte{1})
hash1 := *types.NewHash([]byte{2})
event00 := &pb.Event{
TxHash: hash0,
Data: nil,
@ -666,7 +667,7 @@ func TestChainLedger_AddEvent(t *testing.T) {
ledger.AddEvent(event01)
ledger.AddEvent(event10)
events := ledger.Events(hash0.Hex())
events := ledger.Events(hash0.String())
assert.Equal(t, 2, len(events))
assert.Equal(t, event00, events[0])
assert.Equal(t, event01, events[1])
@ -681,7 +682,7 @@ func genBlockData(height uint64, accounts map[types.Address]*Account, journal *B
BlockHeader: &pb.BlockHeader{
Number: height,
},
BlockHash: sha256.Sum256([]byte{1}),
BlockHash: *types.NewHash([]byte{1}),
Transactions: []*pb.Transaction{{}},
},
Receipts: nil,
@ -705,7 +706,7 @@ BcNwjTDCxyxLNjFKQfMAc6sY6iJs+Ma59WZyC/4uhjE=
return &repo.Repo{
Key: &repo.Key{
PrivKey: privKey,
Address: address.Hex(),
Address: address.String(),
},
}
}

View File

@ -145,7 +145,7 @@ func (l *ChainLedger) FlushDirtyDataAndComputeJournal() (map[types.Address]*Acco
blockJournal := &BlockJournal{
Journals: journals,
ChangedHash: *types.Bytes2Hash(journalHash[:]),
ChangedHash: *types.NewHash(journalHash[:]),
}
l.prevJnlHash = blockJournal.ChangedHash