diff --git a/Makefile b/Makefile index 03e0667..2c051fb 100644 --- a/Makefile +++ b/Makefile @@ -47,12 +47,12 @@ tester: cd tester && $(GO) test -v -run TestTester ## make install: Go install the project -install:mod +install: cd internal/repo && packr $(GO) install -tags '${TAGS}' -ldflags '${GOLDFLAGS}' -modfile go${TAGS}.mod ./cmd/${APP_NAME} @printf "${GREEN}Build bitxhub successfully!${NC}\n" -build: mod +build: cd internal/repo && packr @mkdir -p bin $(GO) build -tags '${TAGS}' -ldflags '${GOLDFLAGS}' -modfile go${TAGS}.mod ./cmd/${APP_NAME} @@ -63,9 +63,6 @@ build: mod linter: golangci-lint run -mod: - @if [ "${TAGS}" != "" ]; then MODS=$(cat ${TAGS}.diff); sed "s?)?${MODS})?" go.mod > go${TAGS}.mod; fi - ## make cluster: Run cluster including 4 nodes cluster:install @cd scripts && bash cluster.sh diff --git a/api/grpc/account.go b/api/grpc/account.go index b6f3449..5d32255 100644 --- a/api/grpc/account.go +++ b/api/grpc/account.go @@ -22,11 +22,11 @@ func (cbs *ChainBrokerService) GetAccountBalance(ctx context.Context, req *pb.Ad return nil, fmt.Errorf("invalid account address: %v", req.Address) } - addr := types.String2Address(req.Address) + addr := types.NewAddressByStr(req.Address) account := cbs.api.Account().GetAccount(addr) - hash := types.Bytes2Hash(account.CodeHash()) + hash := types.NewHash(account.CodeHash()) typ := "normal" @@ -38,7 +38,7 @@ func (cbs *ChainBrokerService) GetAccountBalance(ctx context.Context, req *pb.Ad Type: typ, Balance: account.GetBalance(), ContractCount: account.GetNonce(), - CodeHash: hash, + CodeHash: *hash, } data, err := json.Marshal(ret) @@ -51,7 +51,6 @@ func (cbs *ChainBrokerService) GetAccountBalance(ctx context.Context, req *pb.Ad }, nil } - func (cbs *ChainBrokerService) GetPendingNonceByAccount(ctx context.Context, req *pb.Address) (*pb.Response, error) { nonce := cbs.api.Broker().GetPendingNonceByAccount(req.Address) return &pb.Response{ diff --git a/api/grpc/receipt.go b/api/grpc/receipt.go index eb52971..af24200 100644 --- a/api/grpc/receipt.go +++ b/api/grpc/receipt.go @@ -8,7 +8,7 @@ import ( ) func (cbs *ChainBrokerService) GetReceipt(ctx context.Context, req *pb.TransactionHashMsg) (*pb.Receipt, error) { - hash := types.String2Hash(req.TxHash) + hash := types.NewHashByStr(req.TxHash) return cbs.api.Broker().GetReceipt(hash) } diff --git a/api/grpc/subscribe.go b/api/grpc/subscribe.go index 57c8b59..b8e884f 100644 --- a/api/grpc/subscribe.go +++ b/api/grpc/subscribe.go @@ -26,9 +26,9 @@ func (cbs *ChainBrokerService) Subscribe(req *pb.SubscriptionRequest, server pb. case pb.SubscriptionRequest_BLOCK_HEADER.String(): return cbs.handleBlockHeaderSubscription(server) case pb.SubscriptionRequest_INTERCHAIN_TX_WRAPPER.String(): - return cbs.handleInterchainTxWrapperSubscription(server, types.Bytes2Address(req.Extra).String(), false) + return cbs.handleInterchainTxWrapperSubscription(server, types.NewAddress(req.Extra).String(), false) case pb.SubscriptionRequest_UNION_INTERCHAIN_TX_WRAPPER.String(): - return cbs.handleInterchainTxWrapperSubscription(server, types.Bytes2Address(req.Extra).String(), true) + return cbs.handleInterchainTxWrapperSubscription(server, types.NewAddress(req.Extra).String(), true) } return nil @@ -171,9 +171,9 @@ func (cbs *ChainBrokerService) interStatus(block *pb.Block, interchainMeta *pb.I for _, indices := range interchainMeta.Counter { for _, idx := range indices.Slice { - ibtp, err := txs[idx].GetIBTP() - if err != nil { - return nil, err + ibtp := txs[idx].GetIBTP() + if ibtp == nil { + return nil, fmt.Errorf("ibtp is empty") } status := &InterchainStatus{ diff --git a/api/grpc/transaction.go b/api/grpc/transaction.go index 1084cdb..31ce9c9 100644 --- a/api/grpc/transaction.go +++ b/api/grpc/transaction.go @@ -13,7 +13,7 @@ import ( // SendTransaction handles transaction sent by the client. // If the transaction is valid, it will return the transaction hash. -func (cbs *ChainBrokerService) SendTransaction(ctx context.Context, tx *pb.SendTransactionRequest) (*pb.TransactionHashMsg, error) { +func (cbs *ChainBrokerService) SendTransaction(ctx context.Context, tx *pb.Transaction) (*pb.TransactionHashMsg, error) { if !cbs.api.Broker().OrderReady() { return nil, fmt.Errorf("the system is temporarily unavailable") } @@ -30,7 +30,7 @@ func (cbs *ChainBrokerService) SendTransaction(ctx context.Context, tx *pb.SendT return &pb.TransactionHashMsg{TxHash: hash}, nil } -func (cbs *ChainBrokerService) SendView(_ context.Context, tx *pb.SendTransactionRequest) (*pb.Receipt, error) { +func (cbs *ChainBrokerService) SendView(_ context.Context, tx *pb.Transaction) (*pb.Receipt, error) { if err := cbs.checkTransaction(tx); err != nil { return nil, err } @@ -43,25 +43,21 @@ func (cbs *ChainBrokerService) SendView(_ context.Context, tx *pb.SendTransactio return result, nil } -func (cbs *ChainBrokerService) checkTransaction(tx *pb.SendTransactionRequest) error { - if tx.Data == nil { - return fmt.Errorf("tx data can't be empty") +func (cbs *ChainBrokerService) checkTransaction(tx *pb.Transaction) error { + if tx.Payload == nil && tx.Amount == 0 && tx.IBTP == nil { + return fmt.Errorf("tx payload, ibtp and amount can't all be empty") } - if tx.Data.Type == pb.TransactionData_NORMAL && tx.Data.Amount == 0 { - return fmt.Errorf("amount can't be 0 in transfer tx") - } - - emptyAddress := types.Address{}.Hex() - if tx.From.Hex() == emptyAddress { + emptyAddress := &types.Address{} + if tx.From.String() == emptyAddress.String() { return fmt.Errorf("from can't be empty") } - if tx.From == tx.To { + if tx.From.String() == tx.To.String() { return fmt.Errorf("from can`t be the same as to") } - if tx.To.Hex() == emptyAddress && len(tx.Data.Payload) == 0 { + if tx.To.String() == emptyAddress.String() && len(tx.Payload) == 0 { return fmt.Errorf("can't deploy empty contract") } @@ -81,19 +77,9 @@ func (cbs *ChainBrokerService) checkTransaction(tx *pb.SendTransactionRequest) e return nil } -func (cbs *ChainBrokerService) sendTransaction(req *pb.SendTransactionRequest) (string, error) { - tx := &pb.Transaction{ - Version: req.Version, - From: req.From, - To: req.To, - Timestamp: req.Timestamp, - Data: req.Data, - Nonce: req.Nonce, - Signature: req.Signature, - Extra: req.Extra, - } +func (cbs *ChainBrokerService) sendTransaction(tx *pb.Transaction) (string, error) { tx.TransactionHash = tx.Hash() - ok, _ := asym.Verify(crypto.Secp256k1, tx.Signature, tx.SignHash().Bytes(), tx.From) + ok, _ := asym.Verify(crypto.Secp256k1, tx.Signature, tx.SignHash().Bytes(), *tx.From) if !ok { return "", fmt.Errorf("invalid signature") } @@ -102,21 +88,10 @@ func (cbs *ChainBrokerService) sendTransaction(req *pb.SendTransactionRequest) ( return "", err } - return tx.TransactionHash.Hex(), nil + return tx.TransactionHash.String(), nil } -func (cbs *ChainBrokerService) sendView(req *pb.SendTransactionRequest) (*pb.Receipt, error) { - tx := &pb.Transaction{ - Version: req.Version, - From: req.From, - To: req.To, - Timestamp: req.Timestamp, - Data: req.Data, - Nonce: req.Nonce, - Signature: req.Signature, - Extra: req.Extra, - } - +func (cbs *ChainBrokerService) sendView(tx *pb.Transaction) (*pb.Receipt, error) { result, err := cbs.api.Broker().HandleView(tx) if err != nil { return nil, err @@ -126,7 +101,7 @@ func (cbs *ChainBrokerService) sendView(req *pb.SendTransactionRequest) (*pb.Rec } func (cbs *ChainBrokerService) GetTransaction(ctx context.Context, req *pb.TransactionHashMsg) (*pb.GetTransactionResponse, error) { - hash := types.String2Hash(req.TxHash) + hash := types.NewHashByStr(req.TxHash) tx, err := cbs.api.Broker().GetTransaction(hash) if err != nil { return nil, err diff --git a/cmd/bitxhub/client/transaction.go b/cmd/bitxhub/client/transaction.go index 6233363..0951942 100644 --- a/cmd/bitxhub/client/transaction.go +++ b/cmd/bitxhub/client/transaction.go @@ -3,6 +3,7 @@ package client import ( "encoding/json" "fmt" + "math/rand" "time" "github.com/meshplus/bitxhub-kit/types" @@ -96,32 +97,30 @@ func sendTransaction(ctx *cli.Context) error { return fmt.Errorf("wrong private key: %w", err) } - to := types.String2Address(toString) + to := types.NewAddressByStr(toString) - req := pb.SendTransactionRequest{ - From: from, - To: to, - Timestamp: time.Now().UnixNano(), - Data: &pb.TransactionData{ - Type: pb.TransactionData_Type(txType), - Amount: amount, - }, - Signature: nil, + data := &pb.TransactionData{ + Type: pb.TransactionData_Type(txType), + Amount: amount, + } + payload, err := data.Marshal() + if err != nil { + return err } tx := &pb.Transaction{ From: from, To: to, - Timestamp: req.Timestamp, - Nonce: uint64(req.Nonce), - Data: req.Data, + Timestamp: time.Now().UnixNano(), + Nonce: rand.Uint64(), + Payload: payload, } if err := tx.Sign(key.PrivKey); err != nil { return err } - reqData, err := json.Marshal(req) + reqData, err := json.Marshal(tx) if err != nil { return err } diff --git a/go.mod b/go.mod index d3db84f..4c48543 100644 --- a/go.mod +++ b/go.mod @@ -18,9 +18,9 @@ require ( github.com/hokaccha/go-prettyjson v0.0.0-20190818114111-108c894c2c0e github.com/libp2p/go-libp2p-core v0.5.6 github.com/magiconair/properties v1.8.1 - github.com/meshplus/bitxhub-core v0.1.0-rc1.0.20201016031620-9d2d859c4069 - github.com/meshplus/bitxhub-kit v1.0.1-0.20201020090511-52fcd9cba5dc - github.com/meshplus/bitxhub-model v1.0.0-rc4.0.20201009112846-79d2e6ddf10d + github.com/meshplus/bitxhub-core v0.1.0-rc1.0.20201022032823-4591a8883995 + github.com/meshplus/bitxhub-kit v1.1.2-0.20201021105954-468d0a9d7957 + github.com/meshplus/bitxhub-model v1.1.2-0.20201021152621-0b3c17c54b23 github.com/meshplus/go-lightp2p v0.0.0-20200817105923-6b3aee40fa54 github.com/mitchellh/go-homedir v1.1.0 github.com/multiformats/go-multiaddr v0.2.2 @@ -37,6 +37,7 @@ require ( github.com/tmc/grpc-websocket-proxy v0.0.0-20190109142713-0ad062ec5ee5 github.com/urfave/cli v1.22.1 github.com/wasmerio/go-ext-wasm v0.3.1 + github.com/willf/bitset v1.1.11 // indirect github.com/willf/bloom v2.0.3+incompatible go.uber.org/atomic v1.6.0 google.golang.org/grpc v1.27.1 diff --git a/go.sum b/go.sum index de8c966..d7882d2 100644 --- a/go.sum +++ b/go.sum @@ -41,6 +41,7 @@ github.com/allegro/bigcache v1.2.1-0.20190218064605-e24eb225f156/go.mod h1:Cb/ax github.com/antihax/optional v0.0.0-20180407024304-ca021399b1a6/go.mod h1:V8iCPQYkqmusNa815XgQio277wI47sdRh1dUOLdyC6Q= github.com/aristanetworks/fsnotify v1.4.2/go.mod h1:D/rtu7LpjYM8tRJphJ0hUBYpjai8SfX+aSNsWDTq/Ks= github.com/aristanetworks/glog v0.0.0-20191112221043-67e8567f59f3/go.mod h1:KASm+qXFKs/xjSoWn30NrWBBvdTTQq+UjkhjEJHfSFA= +github.com/aristanetworks/goarista v0.0.0-20170210015632-ea17b1a17847 h1:rtI0fD4oG/8eVokGVPYJEW1F88p1ZNgXiEIs9thEE4A= github.com/aristanetworks/goarista v0.0.0-20170210015632-ea17b1a17847/go.mod h1:D/tb0zPVXnP7fmsLZjtdUhSsumbK/ij54UXjjVgMGxQ= github.com/aristanetworks/goarista v0.0.0-20200310212843-2da4c1f5881b h1:VBFuX8nQQ57A6OGYGOLugx/Sc488F0nNIdTtcmNq9qE= github.com/aristanetworks/goarista v0.0.0-20200310212843-2da4c1f5881b/go.mod h1:QZe5Yh80Hp1b6JxQdpfSEEe8X7hTyTEZSosSrFf/oJE= @@ -53,6 +54,8 @@ github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= github.com/bitxhub/parallel-executor v0.0.0-20201016065313-8057d544998e h1:nz0MelhdC0A8yPGAL2gM/94xD8KgRVjYX0QejiP/f0Q= github.com/bitxhub/parallel-executor v0.0.0-20201016065313-8057d544998e/go.mod h1:rMcZvKgOfyIesmOimA6LXjAvGZyJAXhPPRejEYmsS+k= +github.com/bitxhub/parallel-executor v0.0.0-20201022141235-a2d73478b5a0 h1:GcQzZb6D130tRBPauKjDP1blqOpqXH5OTgr76SECz1s= +github.com/bitxhub/parallel-executor v0.0.0-20201022141235-a2d73478b5a0/go.mod h1:nQGC3gfSjr5iWLTuQdbn9d1HjfXaxV2XsLovIyVSDi8= github.com/btcsuite/btcd v0.0.0-20171128150713-2e60448ffcc6/go.mod h1:Dmm/EzmjnCiweXmzRIAiUWCInVmPgjkzgv5k4tVyXiQ= github.com/btcsuite/btcd v0.0.0-20190115013929-ed77733ec07d/go.mod h1:d3C0AkH6BRcvO8T0UEPu53cnw4IbV63x1bEjildYhO0= github.com/btcsuite/btcd v0.0.0-20190213025234-306aecffea32/go.mod h1:DrZx5ec/dmnfpw9KyYoQyYo7d0KEvTkk/5M/vbZjAr8= @@ -90,6 +93,7 @@ github.com/coreos/go-etcd v2.0.0+incompatible/go.mod h1:Jez6KQU2B/sWsbdaef3ED8Nz github.com/coreos/go-semver v0.2.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk= github.com/coreos/go-semver v0.3.0 h1:wkHLiw0WNATZnSG7epLsujiMCgPAc9xhjJ4tgnAxmfM= github.com/coreos/go-semver v0.3.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk= +github.com/coreos/go-systemd v0.0.0-20190321100706-95778dfbb74e h1:Wf6HqHfScWJN9/ZjdUKyjop4mf3Qdd+1TvvltAvM3m8= github.com/coreos/go-systemd v0.0.0-20190321100706-95778dfbb74e/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4= github.com/coreos/go-systemd v0.0.0-20190719114852-fd7a80b32e1f h1:JOrtw2xFKzlg+cbHpyrpLDmnN1HqhBfnX7WDiW7eG2c= github.com/coreos/go-systemd v0.0.0-20190719114852-fd7a80b32e1f/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4= @@ -97,6 +101,7 @@ github.com/coreos/pkg v0.0.0-20180928190104-399ea9e2e55f h1:lBNOc5arjvs8E5mO2tbp github.com/coreos/pkg v0.0.0-20180928190104-399ea9e2e55f/go.mod h1:E3G3o1h8I7cfcXa63jLwjI0eiQQMgzzUDFVpN/nH/eA= github.com/cpuguy83/go-md2man v1.0.10 h1:BSKMNlYxDvnunlTymqtgONjNnaRV1sTpcovwwjF22jk= github.com/cpuguy83/go-md2man v1.0.10/go.mod h1:SmD6nW6nTyfqj6ABTjUi3V3JVMnlJmwcJI5acqYI6dE= +github.com/cpuguy83/go-md2man/v2 v2.0.0-20190314233015-f79a8a8ca69d h1:U+s90UTSYgptZMwQh2aRr3LuazLJIa+Pg3Kc1ylSYVY= github.com/cpuguy83/go-md2man/v2 v2.0.0-20190314233015-f79a8a8ca69d/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU= github.com/cpuguy83/go-md2man/v2 v2.0.0 h1:EoUDS0afbrsXAZ9YQ9jdu/mZ2sXgT1/2yyNng4PGlyM= github.com/cpuguy83/go-md2man/v2 v2.0.0/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU= @@ -141,6 +146,7 @@ github.com/ethereum/go-ethereum v1.9.18 h1:+vzvufVD7+OfQa07IJP20Z7AGZsJaw0M6JIA/ github.com/ethereum/go-ethereum v1.9.18/go.mod h1:JSSTypSMTkGZtAdAChH2wP5dZEvPGh3nUTuDpH+hNrg= github.com/fastly/go-utils v0.0.0-20180712184237-d95a45783239 h1:Ghm4eQYC0nEPnSJdVkTrXpu9KtoVCSo1hg7mtI7G9KU= github.com/fastly/go-utils v0.0.0-20180712184237-d95a45783239/go.mod h1:Gdwt2ce0yfBxPvZrHkprdPPTTS3N5rwmLE8T22KBXlw= +github.com/fatih/color v1.3.0 h1:YehCCcyeQ6Km0D6+IapqPinWBK6y+0eB5umvZXK9WPs= github.com/fatih/color v1.3.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4= github.com/fatih/color v1.7.0 h1:DkWD4oS2D8LGGgTQ6IvwJJXSL5Vp2ffcQg58nFV38Ys= github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4= @@ -165,6 +171,7 @@ github.com/go-logfmt/logfmt v0.4.0/go.mod h1:3RMwSq7FuexP4Kalkev3ejPJsZTpXXBr9+V github.com/go-ole/go-ole v1.2.1/go.mod h1:7FAglXiTm7HKlQRDeOQ6ZNUHidzCWXuZWq/1dTyBNF8= github.com/go-sourcemap/sourcemap v2.1.2+incompatible/go.mod h1:F8jJfvm2KbVjc5NqelyYJmf/v5J0dwNLS2mL4sNA1Jg= github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY= +github.com/gobuffalo/envy v1.7.0 h1:GlXgaiBkmrYMHco6t4j7SacKO4XUjvh5pwXh0f4uxXU= github.com/gobuffalo/envy v1.7.0/go.mod h1:n7DRkBerg/aorDM8kbduw5dN3oXGswK5liaSCx4T5NI= github.com/gobuffalo/envy v1.9.0 h1:eZR0DuEgVLfeIb1zIKt3bT4YovIMf9O9LXQeCZLXpqE= github.com/gobuffalo/envy v1.9.0/go.mod h1:FurDp9+EDPE4aIUS3ZLyD+7/9fpx7YRt/ukY6jIHf0w= @@ -567,22 +574,40 @@ github.com/mattn/go-runewidth v0.0.4/go.mod h1:LwmH8dsx7+W8Uxz3IHJYH5QSwggIsqBzp github.com/matttproud/golang_protobuf_extensions v1.0.1 h1:4hp9jkHxhMHkqkrB3Ix0jegS5sx/RkqARlsWZ6pIwiU= github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0= github.com/meshplus/bitxhub v1.0.0-rc2/go.mod h1:ijWzPl7GExD3IKXJ0LhV4q680kDy1IFQKd2Kzyzmtl0= -github.com/meshplus/bitxhub-core v0.1.0-rc1 h1:i8/8Ay7McOdgAdeZIMeXRzMSzM0usN+hnkGVyIfrOtU= github.com/meshplus/bitxhub-core v0.1.0-rc1/go.mod h1:ayq95vbGEh/G2nKyPeXPc62zanWhDuusVpIDAHm4Rk0= github.com/meshplus/bitxhub-core v0.1.0-rc1.0.20201016031620-9d2d859c4069 h1:tAKmTgR/I4JbQcrP9I+dFtApQdWc9e7dzG0NqDd65fg= github.com/meshplus/bitxhub-core v0.1.0-rc1.0.20201016031620-9d2d859c4069/go.mod h1:z60hNhn5jgGgQiUOE0AKK2vM3WKQfekhljHjDI5j/Nw= +github.com/meshplus/bitxhub-core v0.1.0-rc1.0.20201021060002-1c1bbd9b125b h1:5t2GrGqn4Y5HwdCVoICFVFGfKdwOgXDtsJFfBXiB/aY= +github.com/meshplus/bitxhub-core v0.1.0-rc1.0.20201021060002-1c1bbd9b125b/go.mod h1:rwnRbid5w7VvQqKTix2yEttI5kaCyCgmV+IZwcewz6Q= +github.com/meshplus/bitxhub-core v0.1.0-rc1.0.20201021153523-274a013bfd41 h1:4D9k/vhslbJjT4e2chBlvLYQrDh7jJ0IxK1gMl0BmJg= +github.com/meshplus/bitxhub-core v0.1.0-rc1.0.20201021153523-274a013bfd41/go.mod h1:/SQKAylZzPup1JTc3WoApLEsB4uV3enXB2ib6jLpYUk= +github.com/meshplus/bitxhub-core v0.1.0-rc1.0.20201022032823-4591a8883995 h1:0QCTie7+Xb+qEKlteh7v39ieiF/QXtOxq0vHUbhAqcQ= +github.com/meshplus/bitxhub-core v0.1.0-rc1.0.20201022032823-4591a8883995/go.mod h1:/SQKAylZzPup1JTc3WoApLEsB4uV3enXB2ib6jLpYUk= github.com/meshplus/bitxhub-kit v1.0.0-rc1/go.mod h1:ra/AhOkPvpElI+wXrB9G6DjdcrdxFU3vMwA5MYKr9D0= github.com/meshplus/bitxhub-kit v1.0.0-rc2/go.mod h1:1XDQRhdVkFDwQH3SgKKyy+cpUyfozNmCqrudDXlh2Oo= github.com/meshplus/bitxhub-kit v1.0.0/go.mod h1:7cWyhXWZfrQ3+EaxkRoXfuiG3Y5R9DXYJomeZKkETW8= github.com/meshplus/bitxhub-kit v1.0.1-0.20200903112208-fb288271c55c/go.mod h1:8Pprmnq+2fFi5kJP0qcbwPl/fe22nro0OamjtwD0LJM= -github.com/meshplus/bitxhub-kit v1.0.1-0.20200914065214-5161497a783c h1:H5RvXIJK9yjV8kqruGI9Ks5aal6PVvcpsMhn6hREtA8= github.com/meshplus/bitxhub-kit v1.0.1-0.20200914065214-5161497a783c/go.mod h1:Whtgcr25HOF6iJv0Ib5/BPnEXq9iNFO89j8JQkElISk= -github.com/meshplus/bitxhub-kit v1.0.1-0.20201020090511-52fcd9cba5dc h1:rB9K68YrxFS4R2JbweF2zDh8Vwk30U00YLgZuiUSUpY= -github.com/meshplus/bitxhub-kit v1.0.1-0.20201020090511-52fcd9cba5dc/go.mod h1:Whtgcr25HOF6iJv0Ib5/BPnEXq9iNFO89j8JQkElISk= +github.com/meshplus/bitxhub-kit v1.1.1 h1:vkPO88oA3+Kpc0N8lIgfj/U52KBuI+633hPbMYt1xm8= +github.com/meshplus/bitxhub-kit v1.1.1/go.mod h1:r4l4iqn0RPJreb/OmoYKfjCjQJrXpZX++6Qc31VG/1k= +github.com/meshplus/bitxhub-kit v1.1.2-0.20201021090332-9830eaa971d4 h1:4nlHdSmzaigzpeMS/bcP60T5/Hwnv3TmGLRFf+9k1t8= +github.com/meshplus/bitxhub-kit v1.1.2-0.20201021090332-9830eaa971d4/go.mod h1:r4l4iqn0RPJreb/OmoYKfjCjQJrXpZX++6Qc31VG/1k= +github.com/meshplus/bitxhub-kit v1.1.2-0.20201021105954-468d0a9d7957 h1:1a3wYo2HQw9/yg5LfAPJ1En90pPbMwRlaVssxOLG97w= +github.com/meshplus/bitxhub-kit v1.1.2-0.20201021105954-468d0a9d7957/go.mod h1:r4l4iqn0RPJreb/OmoYKfjCjQJrXpZX++6Qc31VG/1k= github.com/meshplus/bitxhub-model v1.0.0-rc3/go.mod h1:ZCctQIYTlE3vJ8Lhkrgs9bWwNA+Dw4JzojOSIzLVU6E= github.com/meshplus/bitxhub-model v1.0.0-rc4.0.20200514093243-7e8ae60d1c19/go.mod h1:QK8aACbxtZEA3Hk1BOCirW0uxMWLsMrLDpWz9FweIKM= github.com/meshplus/bitxhub-model v1.0.0-rc4.0.20201009112846-79d2e6ddf10d h1:q4Vig+IVhBvARLyeOsFw8gAdor0ajiBl6lGch1N65sk= github.com/meshplus/bitxhub-model v1.0.0-rc4.0.20201009112846-79d2e6ddf10d/go.mod h1:QK8aACbxtZEA3Hk1BOCirW0uxMWLsMrLDpWz9FweIKM= +github.com/meshplus/bitxhub-model v1.1.1 h1:/0Si29e14YW1GUbkJbCL8A70yXzxyiV/u36kxFC+gqI= +github.com/meshplus/bitxhub-model v1.1.1/go.mod h1:lUl9vPZXM9tP+B0ABRW/2eOW/6KCmjFTdoiTj5Vut/A= +github.com/meshplus/bitxhub-model v1.1.2-0.20201021121200-409ba3cf9d4b h1:cyK/HwEygdDhZGXUVzd/EoqXmL38dBum1aWEwj7IPks= +github.com/meshplus/bitxhub-model v1.1.2-0.20201021121200-409ba3cf9d4b/go.mod h1:lUl9vPZXM9tP+B0ABRW/2eOW/6KCmjFTdoiTj5Vut/A= +github.com/meshplus/bitxhub-model v1.1.2-0.20201021121624-82edb1eb4937 h1:FILaXFyfTDqP4p0Vbg37giRv1LyWdIPLGQ/3zd3U7fs= +github.com/meshplus/bitxhub-model v1.1.2-0.20201021121624-82edb1eb4937/go.mod h1:lUl9vPZXM9tP+B0ABRW/2eOW/6KCmjFTdoiTj5Vut/A= +github.com/meshplus/bitxhub-model v1.1.2-0.20201021151909-ce32cce89a79 h1:P7JByZx34rUbplyRKyOWMdWJ5t6KAhlZ9JoPiII7vr0= +github.com/meshplus/bitxhub-model v1.1.2-0.20201021151909-ce32cce89a79/go.mod h1:4qWBZx5wv7WZzUqiuBsbkQqQ2Ju8aOFpsoNpBBNy8Us= +github.com/meshplus/bitxhub-model v1.1.2-0.20201021152621-0b3c17c54b23 h1:ys+2VjPrt6nr5xEVgRsVxowipkF425IOcI5HV53M5bA= +github.com/meshplus/bitxhub-model v1.1.2-0.20201021152621-0b3c17c54b23/go.mod h1:4qWBZx5wv7WZzUqiuBsbkQqQ2Ju8aOFpsoNpBBNy8Us= github.com/meshplus/go-bitxhub-client v1.0.0-rc3/go.mod h1:FpiCyf6KhydcqthrHdvvPhbPIcD92b+Ju8T7WvQtSyM= github.com/meshplus/go-lightp2p v0.0.0-20200817105923-6b3aee40fa54 h1:5Ip5AB7SxxQHg5SRtf2cCOI2wy1p75MQB12soPtPyf8= github.com/meshplus/go-lightp2p v0.0.0-20200817105923-6b3aee40fa54/go.mod h1:G89UJaeqCQFxFdp8wzy1AdKfMtDEhpySau0pjDNeeaw= @@ -717,6 +742,7 @@ github.com/prometheus/common v0.9.1/go.mod h1:yhUN8i9wzaXS3w1O07YhxHEBxD+W35wd8b github.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= github.com/prometheus/procfs v0.0.0-20190507164030-5867b95ac084/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA= github.com/prometheus/procfs v0.0.2/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA= +github.com/prometheus/procfs v0.0.8 h1:+fpWZdT24pJBiqJdAwYBjPSk+5YmQzYNPYzQsdzLkt8= github.com/prometheus/procfs v0.0.8/go.mod h1:7Qr8sr6344vo1JqZ6HhLceV9o3AJ1Ff+GxbHq6oeK9A= github.com/prometheus/procfs v0.0.10 h1:QJQN3jYQhkamO4mhfUWqdDH2asK7ONOI9MTWjyAxNKM= github.com/prometheus/procfs v0.0.10/go.mod h1:7Qr8sr6344vo1JqZ6HhLceV9o3AJ1Ff+GxbHq6oeK9A= @@ -732,6 +758,7 @@ github.com/rjeczalik/notify v0.9.1/go.mod h1:rKwnCoCGeuQnwBtTSPL9Dad03Vh2n40ePRr github.com/rogpeppe/fastuuid v0.0.0-20150106093220-6724a57986af/go.mod h1:XWv6SoW27p1b0cqNHllgS5HIMJraePCO15w5zCzIWYg= github.com/rogpeppe/fastuuid v1.2.0/go.mod h1:jVj6XXZzXRy/MSR5jhDC/2q6DgLz+nrA6LYCDYWNEvQ= github.com/rogpeppe/go-internal v1.1.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= +github.com/rogpeppe/go-internal v1.3.0 h1:RR9dF3JtopPvtkroDZuVD7qquD0bnHlKSqaQhgwt8yk= github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= github.com/rogpeppe/go-internal v1.3.2/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc= github.com/rogpeppe/go-internal v1.5.2 h1:qLvObTrvO/XRCqmkKxUlOBc48bI3efyDuAZe25QiF0w= @@ -775,6 +802,7 @@ github.com/spf13/cobra v0.0.1/go.mod h1:1l0Ry5zgKvJasoi3XT1TypsSe7PqH0Sj9dhYf7v3 github.com/spf13/cobra v0.0.5/go.mod h1:3K3wKZymM7VvHMDS9+Akkh4K60UwM26emMESw8tLCHU= github.com/spf13/jwalterweatherman v1.0.0 h1:XHEdyB+EcvlqZamSM4ZOMGlc93t6AcsBEu9Gc1vn7yk= github.com/spf13/jwalterweatherman v1.0.0/go.mod h1:cQK4TGJAtQXfYWX+Ddv3mKDzgVb68N+wFjFa4jdeBTo= +github.com/spf13/pflag v1.0.3 h1:zPAT6CGy6wXeQ7NtTnaTerfKOsV6V6F8agHXFiazDkg= github.com/spf13/pflag v1.0.3/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4= github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= @@ -788,6 +816,7 @@ github.com/steakknife/bloomfilter v0.0.0-20180922174646-6819c0d2a570/go.mod h1:8 github.com/steakknife/hamming v0.0.0-20180906055917-c99c65617cd3/go.mod h1:hpGUWaI9xL8pRQCTXQgocU38Qw1g0Us7n5PxxTwTCYU= github.com/streadway/amqp v0.0.0-20190827072141-edfb9018d271/go.mod h1:AZpEONHx3DKn8O/DFsRAY58/XVQiIPMTMB1SddzLXVw= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.1.1 h1:2vfRuCMp5sSVIDSqO8oNnWJq7mPa6KVP3iPIwFBuy8A= github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.2.0 h1:Hbg2NidpLE8veEBkEZTL3CvlkUIVzuU9jDplZO54c48= github.com/stretchr/objx v0.2.0/go.mod h1:qt09Ya8vawLte6SNmTgCsAVtYtaKzEcn8ATUoHMkEqE= @@ -841,6 +870,8 @@ github.com/whyrusleeping/multiaddr-filter v0.0.0-20160516205228-e903e4adabd7 h1: github.com/whyrusleeping/multiaddr-filter v0.0.0-20160516205228-e903e4adabd7/go.mod h1:X2c0RVCI1eSUFI8eLcY3c0423ykwiUdxLJtkDvruhjI= github.com/willf/bitset v1.1.10 h1:NotGKqX0KwQ72NUzqrjZq5ipPNDQex9lo3WpaS8L2sc= github.com/willf/bitset v1.1.10/go.mod h1:RjeCKbqT1RxIR/KWY6phxZiaY1IyutSBfGjNPySAYV4= +github.com/willf/bitset v1.1.11 h1:N7Z7E9UvjW+sGsEl7k/SJrvY2reP1A07MrGuCjIOjRE= +github.com/willf/bitset v1.1.11/go.mod h1:83CECat5yLh5zVOf4P1ErAgKA5UDvKtgyUABdr3+MjI= github.com/willf/bloom v2.0.3+incompatible h1:QDacWdqcAUI1MPOwIQZRy9kOR7yxfyEmxX8Wdm2/JPA= github.com/willf/bloom v2.0.3+incompatible/go.mod h1:MmAltL9pDMNTrvUkxdg0k0q5I0suxmuwp3KbyrZLOZ8= github.com/wonderivan/logger v1.0.0/go.mod h1:NObMfQ3WOLKfYEZuGeZQfuQfSPE5+QNgRddVMzsAT/k= @@ -991,6 +1022,7 @@ golang.org/x/tools v0.0.0-20190624180213-70d37148ca0c/go.mod h1:/rFqwRUd4F7ZHNgw golang.org/x/tools v0.0.0-20191029041327-9cc4af7d6b2c/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20191029190741-b9c20aec41a5/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20191108193012-7d206e10da11/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191216052735-49a3e744a425 h1:VvQyQJN0tSuecqgcIxMWnnfG5kSmgy9KZR9sW3W5QeA= golang.org/x/tools v0.0.0-20191216052735-49a3e744a425/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= golang.org/x/tools v0.0.0-20200221224223-e1da425f72fd h1:hHkvGJK23seRCflePJnVa9IMv8fsuavSCWKd11kDQFs= golang.org/x/tools v0.0.0-20200221224223-e1da425f72fd/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= diff --git a/goent.mod b/goent.mod new file mode 100644 index 0000000..c5f5eff --- /dev/null +++ b/goent.mod @@ -0,0 +1,49 @@ +module github.com/meshplus/bitxhub + +require ( + github.com/Rican7/retry v0.1.0 + github.com/bitxhub/parallel-executor v0.0.0-20201022141235-a2d73478b5a0 + github.com/cbergoon/merkletree v0.2.0 + github.com/common-nighthawk/go-figure v0.0.0-20190529165535-67e0ed34491a + github.com/coreos/etcd v3.3.18+incompatible + github.com/ethereum/go-ethereum v1.9.18 + github.com/gobuffalo/packd v1.0.0 + github.com/gobuffalo/packr v1.30.1 + github.com/gogo/protobuf v1.3.1 + github.com/golang/mock v1.4.3 + github.com/golang/protobuf v1.4.2 // indirect + github.com/google/btree v1.0.0 + github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0 + github.com/grpc-ecosystem/grpc-gateway v1.13.0 + github.com/hashicorp/golang-lru v0.5.4 + github.com/hokaccha/go-prettyjson v0.0.0-20190818114111-108c894c2c0e + github.com/libp2p/go-libp2p-core v0.5.6 + github.com/magiconair/properties v1.8.1 + github.com/meshplus/bitxhub-core v0.1.0-rc1.0.20201022032823-4591a8883995 + github.com/meshplus/bitxhub-kit v1.1.2-0.20201021105954-468d0a9d7957 + github.com/meshplus/bitxhub-model v1.1.2-0.20201021152621-0b3c17c54b23 + github.com/meshplus/go-lightp2p v0.0.0-20200817105923-6b3aee40fa54 + github.com/mitchellh/go-homedir v1.1.0 + github.com/multiformats/go-multiaddr v0.2.2 + github.com/orcaman/concurrent-map v0.0.0-20190826125027-8c72a8bb44f6 + github.com/pkg/errors v0.9.1 + github.com/prometheus/client_golang v1.5.0 + github.com/rs/cors v1.7.0 + github.com/sirupsen/logrus v1.6.0 + github.com/spf13/cast v1.3.0 + github.com/spf13/viper v1.6.1 + github.com/stretchr/testify v1.6.0 + github.com/syndtr/goleveldb v1.0.1-0.20190923125748-758128399b1d + github.com/tidwall/gjson v1.3.5 + github.com/tmc/grpc-websocket-proxy v0.0.0-20190109142713-0ad062ec5ee5 + github.com/urfave/cli v1.22.1 + github.com/wasmerio/go-ext-wasm v0.3.1 + github.com/willf/bitset v1.1.11 // indirect + github.com/willf/bloom v2.0.3+incompatible + go.uber.org/atomic v1.6.0 + google.golang.org/grpc v1.27.1 +) + +replace github.com/golang/protobuf v1.4.2 => github.com/golang/protobuf v1.3.2 + +go 1.14 diff --git a/internal/app/bitxhub.go b/internal/app/bitxhub.go index fc28db6..a5642d8 100644 --- a/internal/app/bitxhub.go +++ b/internal/app/bitxhub.go @@ -54,7 +54,7 @@ func NewBitXHub(rep *repo.Repo) (*BitXHub, error) { if !rep.Config.Solo { for i, node := range rep.NetworkConfig.Nodes { - m[node.ID] = types.String2Address(rep.Genesis.Addresses[i]) + m[node.ID] = *types.NewAddressByStr(rep.Genesis.Addresses[i]) } } @@ -67,7 +67,7 @@ func NewBitXHub(rep *repo.Repo) (*BitXHub, error) { order.WithPeerManager(bxh.PeerMgr), order.WithLogger(loggers.Logger(loggers.Order)), order.WithApplied(chainMeta.Height), - order.WithDigest(chainMeta.BlockHash.Hex()), + order.WithDigest(chainMeta.BlockHash.String()), order.WithGetChainMetaFunc(bxh.Ledger.GetChainMeta), order.WithGetTransactionFunc(bxh.Ledger.GetTransaction), ) @@ -170,7 +170,7 @@ func NewTesterBitXHub(rep *repo.Repo) (*BitXHub, error) { if !rep.Config.Solo { for i, node := range rep.NetworkConfig.Nodes { - m[node.ID] = types.String2Address(rep.Genesis.Addresses[i]) + m[node.ID] = *types.NewAddressByStr(rep.Genesis.Addresses[i]) } } @@ -183,7 +183,7 @@ func NewTesterBitXHub(rep *repo.Repo) (*BitXHub, error) { order.WithPeerManager(bxh.PeerMgr), order.WithLogger(loggers.Logger(loggers.Order)), order.WithApplied(chainMeta.Height), - order.WithDigest(chainMeta.BlockHash.Hex()), + order.WithDigest(chainMeta.BlockHash.String()), order.WithGetChainMetaFunc(bxh.Ledger.GetChainMeta), order.WithGetTransactionFunc(bxh.Ledger.GetTransaction), ) diff --git a/internal/app/feedhub.go b/internal/app/feedhub.go index dca6622..ee4b39b 100644 --- a/internal/app/feedhub.go +++ b/internal/app/feedhub.go @@ -38,7 +38,7 @@ func (bxh *BitXHub) listenEvent() { for { select { case ev := <-blockCh: - go bxh.Order.ReportState(ev.Block.BlockHeader.Number, ev.Block.BlockHash) + go bxh.Order.ReportState(ev.Block.BlockHeader.Number, *ev.Block.BlockHash) go bxh.Router.PutBlockAndMeta(ev.Block, ev.InterchainMeta) case ev := <-orderMsgCh: go func() { diff --git a/internal/constant/constant.go b/internal/constant/constant.go index 6d38236..b6abd9c 100644 --- a/internal/constant/constant.go +++ b/internal/constant/constant.go @@ -14,8 +14,8 @@ const ( AssetExchangeContractAddr BoltContractAddress = "0x0000000000000000000000000000000000000010" ) -func (addr BoltContractAddress) Address() types.Address { - return types.String2Address(string(addr)) +func (addr BoltContractAddress) Address() *types.Address { + return types.NewAddressByStr(string(addr)) } func (addr BoltContractAddress) String() string { diff --git a/internal/coreapi/account.go b/internal/coreapi/account.go index b05a1b2..5c52f84 100644 --- a/internal/coreapi/account.go +++ b/internal/coreapi/account.go @@ -10,6 +10,6 @@ type AccountAPI CoreAPI var _ api.AccountAPI = (*AccountAPI)(nil) -func (api *AccountAPI) GetAccount(addr types.Address) *ledger.Account { +func (api *AccountAPI) GetAccount(addr *types.Address) *ledger.Account { return api.bxh.Ledger.GetAccount(addr) } diff --git a/internal/coreapi/api/api.go b/internal/coreapi/api/api.go index a2cf8c2..c3b44c0 100644 --- a/internal/coreapi/api/api.go +++ b/internal/coreapi/api/api.go @@ -20,9 +20,9 @@ type CoreAPI interface { type BrokerAPI interface { HandleTransaction(tx *pb.Transaction) error HandleView(tx *pb.Transaction) (*pb.Receipt, error) - GetTransaction(types.Hash) (*pb.Transaction, error) - GetTransactionMeta(types.Hash) (*pb.TransactionMeta, error) - GetReceipt(types.Hash) (*pb.Receipt, error) + GetTransaction(*types.Hash) (*pb.Transaction, error) + GetTransactionMeta(*types.Hash) (*pb.TransactionMeta, error) + GetReceipt(*types.Hash) (*pb.Receipt, error) GetBlock(mode string, key string) (*pb.Block, error) GetBlocks(start uint64, end uint64) ([]*pb.Block, error) GetPendingNonceByAccount(account string) uint64 @@ -59,5 +59,5 @@ type FeedAPI interface { } type AccountAPI interface { - GetAccount(addr types.Address) *ledger.Account + GetAccount(addr *types.Address) *ledger.Account } diff --git a/internal/coreapi/broker.go b/internal/coreapi/broker.go index 8101870..5a0a47e 100644 --- a/internal/coreapi/broker.go +++ b/internal/coreapi/broker.go @@ -44,15 +44,15 @@ func (b *BrokerAPI) HandleView(tx *pb.Transaction) (*pb.Receipt, error) { return receipts[0], nil } -func (b *BrokerAPI) GetTransaction(hash types.Hash) (*pb.Transaction, error) { +func (b *BrokerAPI) GetTransaction(hash *types.Hash) (*pb.Transaction, error) { return b.bxh.Ledger.GetTransaction(hash) } -func (b *BrokerAPI) GetTransactionMeta(hash types.Hash) (*pb.TransactionMeta, error) { +func (b *BrokerAPI) GetTransactionMeta(hash *types.Hash) (*pb.TransactionMeta, error) { return b.bxh.Ledger.GetTransactionMeta(hash) } -func (b *BrokerAPI) GetReceipt(hash types.Hash) (*pb.Receipt, error) { +func (b *BrokerAPI) GetReceipt(hash *types.Hash) (*pb.Receipt, error) { return b.bxh.Ledger.GetReceipt(hash) } @@ -77,7 +77,7 @@ func (b *BrokerAPI) GetBlock(mode string, value string) (*pb.Block, error) { } return b.bxh.Ledger.GetBlock(height) case "HASH": - return b.bxh.Ledger.GetBlockByHash(types.String2Hash(value)) + return b.bxh.Ledger.GetBlockByHash(types.NewHashByStr(value)) default: return nil, fmt.Errorf("wrong args about getting block: %s", mode) } diff --git a/internal/executor/contracts/appchain_manager.go b/internal/executor/contracts/appchain_manager.go index 25678c2..6e94791 100644 --- a/internal/executor/contracts/appchain_manager.go +++ b/internal/executor/contracts/appchain_manager.go @@ -5,7 +5,6 @@ import ( "strconv" appchainMgr "github.com/meshplus/bitxhub-core/appchain-mgr" - "github.com/meshplus/bitxhub-model/pb" "github.com/meshplus/bitxhub/internal/constant" "github.com/meshplus/bitxhub/pkg/vm/boltvm" diff --git a/internal/executor/contracts/contracts_test.go b/internal/executor/contracts/contracts_test.go index 108cf12..daab5af 100644 --- a/internal/executor/contracts/contracts_test.go +++ b/internal/executor/contracts/contracts_test.go @@ -20,8 +20,8 @@ func TestAppchainManager_Appchain(t *testing.T) { mockCtl := gomock.NewController(t) mockStub := mock_stub.NewMockStub(mockCtl) - addr0 := types.Address{0}.String() - addr1 := types.Address{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.Address{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.Address{}.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.Address{}.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.Address{}.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.Address{0}.String() - to := types.Address{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) @@ -252,7 +252,7 @@ func TestInterchainManager_HandleIBTP(t *testing.T) { mockStub.EXPECT().AddObject(gomock.Any(), gomock.Any()).AnyTimes() mockStub.EXPECT().GetTxIndex().Return(uint64(1)).AnyTimes() mockStub.EXPECT().PostInterchainEvent(gomock.Any()).AnyTimes() - mockStub.EXPECT().GetTxHash().Return(types.Hash{}).AnyTimes() + mockStub.EXPECT().GetTxHash().Return(&types.Hash{}).AnyTimes() gomock.InOrder(f1, f2) im := &InterchainManager{mockStub} @@ -362,8 +362,8 @@ func TestInterchainManager_GetIBTPByID(t *testing.T) { mockCtl := gomock.NewController(t) mockStub := mock_stub.NewMockStub(mockCtl) - from := types.Address{}.String() - to := types.Address{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.Address{0}.String(), types.Address{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.Address{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.Address{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.Address{0}.String(), types.Address{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.Address{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.Address{0}.String(), types.Address{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.Address{0}.String(), types.Address{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.Address{0}.String() - id1 := types.Address{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.Address{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.Address{0}.String() - id1 := types.Address{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.Address{0}.String() - id1 := types.Address{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.Hash{}.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.Address{0}.String() - to := types.Address{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.Address{0}.String() - to := types.Address{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.Address{0}.String() - to := types.Address{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.Address{0}.String() - to := types.Address{1}.String() + from := types.NewAddress([]byte{0}).String() + to := types.NewAddress([]byte{1}).String() aer := AssetExchangeRecord{ Chain0: from, Chain1: to, diff --git a/internal/executor/contracts/interchain.go b/internal/executor/contracts/interchain.go index dc41798..4bbac0c 100755 --- a/internal/executor/contracts/interchain.go +++ b/internal/executor/contracts/interchain.go @@ -6,11 +6,9 @@ import ( "fmt" "strings" - "github.com/meshplus/bitxhub-kit/crypto" - - "github.com/meshplus/bitxhub-kit/crypto/asym" - appchainMgr "github.com/meshplus/bitxhub-core/appchain-mgr" + "github.com/meshplus/bitxhub-kit/crypto" + "github.com/meshplus/bitxhub-kit/crypto/asym" "github.com/meshplus/bitxhub-kit/types" "github.com/meshplus/bitxhub-model/pb" "github.com/meshplus/bitxhub/internal/constant" @@ -382,14 +380,15 @@ func (x *InterchainManager) checkUnionIBTP(app *appchainMgr.Appchain, ibtp *pb.I threshold := (len(validators.Addresses) - 1) / 3 counter := 0 - hash := sha256.Sum256([]byte(ibtp.Hash().String())) + ibtpHash := ibtp.Hash() + hash := sha256.Sum256([]byte(ibtpHash.String())) for v, sign := range signs.Sign { if _, ok := m[v]; !ok { return fmt.Errorf("wrong validator: %s", v) } delete(m, v) - addr := types.String2Address(v) - ok, _ := asym.Verify(crypto.Secp256k1, sign, hash[:], addr) + addr := types.NewAddressByStr(v) + ok, _ := asym.Verify(crypto.Secp256k1, sign, hash[:], *addr) if ok { counter++ } diff --git a/internal/executor/executor.go b/internal/executor/executor.go index e87a83d..0def53a 100755 --- a/internal/executor/executor.go +++ b/internal/executor/executor.go @@ -38,7 +38,7 @@ type BlockExecutor struct { ibtpVerify proof.Verify validationEngine validator.Engine currentHeight uint64 - currentBlockHash types.Hash + currentBlockHash *types.Hash wasmInstances map[string]wasmer.Instance txsExecutor agency.TxsExecutor blockFeed event.Feed @@ -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") diff --git a/internal/executor/executor_test.go b/internal/executor/executor_test.go index 9a14acf..e3fe0e0 100644 --- a/internal/executor/executor_test.go +++ b/internal/executor/executor_test.go @@ -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.NewHash([]byte(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.NewHash([]byte(from)), Data: data, Interchain: true, } @@ -98,7 +98,7 @@ func TestBlockExecutor_ExecuteBlock(t *testing.T) { mockLedger.EXPECT().SetCode(gomock.Any(), gomock.Any()).AnyTimes() mockLedger.EXPECT().GetCode(gomock.Any()).Return([]byte("10")).AnyTimes() mockLedger.EXPECT().PersistExecutionResult(gomock.Any(), gomock.Any(), gomock.Any()).Return(nil).AnyTimes() - mockLedger.EXPECT().FlushDirtyDataAndComputeJournal().Return(make(map[types.Address]*ledger.Account), &ledger.BlockJournal{}).AnyTimes() + mockLedger.EXPECT().FlushDirtyDataAndComputeJournal().Return(make(map[string]*ledger.Account), &ledger.BlockJournal{ChangedHash: &types.Hash{}}).AnyTimes() mockLedger.EXPECT().PersistBlockData(gomock.Any()).AnyTimes() logger := log.NewWithModule("executor") @@ -114,20 +114,20 @@ func TestBlockExecutor_ExecuteBlock(t *testing.T) { // set tx of TransactionData_BVM type ibtp1 := mockIBTP(t, 1, pb.IBTP_INTERCHAIN) BVMData := mockTxData(t, pb.TransactionData_INVOKE, pb.TransactionData_BVM, ibtp1) - BVMTx := mockTx(BVMData) + BVMTx := mockTx(t, BVMData) txs = append(txs, BVMTx) // set tx of TransactionData_XVM type ibtp2 := mockIBTP(t, 2, pb.IBTP_INTERCHAIN) XVMData := mockTxData(t, pb.TransactionData_INVOKE, pb.TransactionData_XVM, ibtp2) - XVMTx := mockTx(XVMData) + XVMTx := mockTx(t, XVMData) txs = append(txs, XVMTx) // set tx of TransactionData_NORMAL type ibtp3 := mockIBTP(t, 3, pb.IBTP_INTERCHAIN) NormalData := mockTxData(t, pb.TransactionData_NORMAL, pb.TransactionData_XVM, ibtp3) - NormalTx := mockTx(NormalData) + NormalTx := mockTx(t, NormalData) txs = append(txs, NormalTx) // set tx with empty transaction data - emptyDataTx := mockTx(nil) + emptyDataTx := mockTx(t, nil) txs = append(txs, emptyDataTx) // set signature for txs @@ -137,10 +137,11 @@ func TestBlockExecutor_ExecuteBlock(t *testing.T) { sig, err := privKey.Sign(tx.SignHash().Bytes()) assert.Nil(t, err) tx.Signature = sig + tx.TransactionHash = tx.Hash() } // set invalid signature tx - invalidTx := mockTx(nil) - invalidTx.From = types.String2Address(from) + invalidTx := mockTx(t, nil) + 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,17 +185,19 @@ 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) + contractAddr := constant.InterchainContractAddr.Address() + mockLedger.EXPECT().GetChainMeta().Return(chainMeta).AnyTimes() mockLedger.EXPECT().Events(gomock.Any()).Return(nil).AnyTimes() mockLedger.EXPECT().Commit(gomock.Any(), gomock.Any(), gomock.Any()).Return(nil).AnyTimes() mockLedger.EXPECT().Clear().AnyTimes() - mockLedger.EXPECT().GetState(constant.InterchainContractAddr.Address(), []byte(fmt.Sprintf("index-tx-%s", id))).Return(true, val).AnyTimes() + mockLedger.EXPECT().GetState(contractAddr, []byte(fmt.Sprintf("index-tx-%s", id))).Return(true, val).AnyTimes() mockLedger.EXPECT().PersistExecutionResult(gomock.Any(), gomock.Any(), gomock.Any()).Return(nil).AnyTimes() - mockLedger.EXPECT().FlushDirtyDataAndComputeJournal().Return(make(map[types.Address]*ledger.Account), &ledger.BlockJournal{}).AnyTimes() + mockLedger.EXPECT().FlushDirtyDataAndComputeJournal().Return(make(map[string]*ledger.Account), &ledger.BlockJournal{}).AnyTimes() mockLedger.EXPECT().PersistBlockData(gomock.Any()).AnyTimes() logger := log.NewWithModule("executor") @@ -203,7 +206,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, contractAddr, "GetIBTPByID", pb.String(id)) assert.Nil(t, err) txs = append(txs, tx) @@ -230,16 +233,24 @@ func mockBlock(blockNumber uint64, txs []*pb.Transaction) *pb.Block { Number: blockNumber, Timestamp: time.Now().UnixNano(), } - return &pb.Block{ + block := &pb.Block{ BlockHeader: header, Transactions: txs, } + block.BlockHash = block.Hash() + + return block } -func mockTx(data *pb.TransactionData) *pb.Transaction { +func mockTx(t *testing.T, data *pb.TransactionData) *pb.Transaction { + var content []byte + if data != nil { + content, _ = data.Marshal() + } return &pb.Transaction{ - Data: data, - Nonce: uint64(rand.Int63()), + To: randAddress(t), + Payload: content, + Nonce: uint64(rand.Int63()), } } @@ -305,25 +316,30 @@ 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, + Amount: 1, } - err := tx.Sign(privKey) + err = tx.Sign(privKey) require.Nil(t, err) tx.TransactionHash = tx.Hash() return tx } -func loadAdminKey(t *testing.T) (crypto.PrivateKey, types.Address) { +func loadAdminKey(t *testing.T) (crypto.PrivateKey, *types.Address) { privKey, err := asym.RestorePrivateKey(filepath.Join("testdata", "key.json"), keyPassword) require.Nil(t, err) @@ -333,7 +349,7 @@ func loadAdminKey(t *testing.T) (crypto.PrivateKey, types.Address) { return privKey, from } -func randAddress(t *testing.T) types.Address { +func randAddress(t *testing.T) *types.Address { privKey, err := asym.GenerateKeyPair(crypto.Secp256k1) require.Nil(t, err) address, err := privKey.PublicKey().Address() @@ -342,15 +358,15 @@ func randAddress(t *testing.T) types.Address { return address } -func genBVMContractTransaction(privateKey crypto.PrivateKey, nonce uint64, address types.Address, method string, args ...*pb.Arg) (*pb.Transaction, error) { +func genBVMContractTransaction(privateKey crypto.PrivateKey, nonce uint64, address *types.Address, method string, args ...*pb.Arg) (*pb.Transaction, error) { return genContractTransaction(pb.TransactionData_BVM, privateKey, nonce, address, method, args...) } -func genXVMContractTransaction(privateKey crypto.PrivateKey, nonce uint64, address types.Address, method string, args ...*pb.Arg) (*pb.Transaction, error) { +func genXVMContractTransaction(privateKey crypto.PrivateKey, nonce uint64, address *types.Address, method string, args ...*pb.Arg) (*pb.Transaction, error) { return genContractTransaction(pb.TransactionData_XVM, privateKey, nonce, address, method, args...) } -func genContractTransaction(vmType pb.TransactionData_VMType, privateKey crypto.PrivateKey, nonce uint64, address types.Address, method string, args ...*pb.Arg) (*pb.Transaction, error) { +func genContractTransaction(vmType pb.TransactionData_VMType, privateKey crypto.PrivateKey, nonce uint64, address *types.Address, method string, args ...*pb.Arg) (*pb.Transaction, error) { from, err := privateKey.PublicKey().Address() if err != nil { return nil, err @@ -372,10 +388,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, To: address, - Data: td, + Payload: pld, Timestamp: time.Now().UnixNano(), Nonce: nonce, } @@ -448,7 +469,7 @@ BcNwjTDCxyxLNjFKQfMAc6sY6iJs+Ma59WZyC/4uhjE= return &repo.Repo{ Key: &repo.Key{ PrivKey: privKey, - Address: address.Hex(), + Address: address.String(), }, } } diff --git a/internal/executor/handle.go b/internal/executor/handle.go index c946b81..235ed9a 100755 --- a/internal/executor/handle.go +++ b/internal/executor/handle.go @@ -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)) @@ -104,7 +104,7 @@ func (exec *BlockExecutor) listenPreExecuteEvent() { } } -func (exec *BlockExecutor) buildTxMerkleTree(txs []*pb.Transaction) (types.Hash, []types.Hash, error) { +func (exec *BlockExecutor) buildTxMerkleTree(txs []*pb.Transaction) (*types.Hash, []types.Hash, error) { var ( groupCnt = len(exec.txsExecutor.GetInterchainCounter()) + 1 wg = sync.WaitGroup{} @@ -120,7 +120,7 @@ func (exec *BlockExecutor) buildTxMerkleTree(txs []*pb.Transaction) (types.Hash, txHashes := make([]merkletree.Content, 0, len(txIndexes)) for _, txIndex := range txIndexes { - txHashes = append(txHashes, pb.TransactionHash(txs[txIndex].TransactionHash.Bytes())) + txHashes = append(txHashes, txs[txIndex].TransactionHash) } hash, err := calcMerkleRoot(txHashes) @@ -131,13 +131,13 @@ func (exec *BlockExecutor) buildTxMerkleTree(txs []*pb.Transaction) (types.Hash, lock.Lock() defer lock.Unlock() - l2Roots = append(l2Roots, hash) + l2Roots = append(l2Roots, *hash) }(addr, txIndexes) } txHashes := make([]merkletree.Content, 0, len(exec.txsExecutor.GetNormalTxs())) for _, txHash := range exec.txsExecutor.GetNormalTxs() { - txHashes = append(txHashes, pb.TransactionHash(txHash.Bytes())) + txHashes = append(txHashes, txHash) } hash, err := calcMerkleRoot(txHashes) @@ -146,12 +146,12 @@ func (exec *BlockExecutor) buildTxMerkleTree(txs []*pb.Transaction) (types.Hash, } lock.Lock() - l2Roots = append(l2Roots, hash) + l2Roots = append(l2Roots, *hash) lock.Unlock() wg.Wait() if errorCnt != 0 { - return types.Hash{}, nil, fmt.Errorf("build tx merkle tree error") + return nil, nil, fmt.Errorf("build tx merkle tree error") } sort.Slice(l2Roots, func(i, j int) bool { @@ -160,11 +160,11 @@ func (exec *BlockExecutor) buildTxMerkleTree(txs []*pb.Transaction) (types.Hash, contents := make([]merkletree.Content, 0, groupCnt) for _, l2Root := range l2Roots { - contents = append(contents, pb.TransactionHash(l2Root.Bytes())) + contents = append(contents, &l2Root) } root, err := calcMerkleRoot(contents) if err != nil { - return types.Hash{}, nil, err + return nil, nil, err } return root, l2Roots, nil @@ -186,7 +186,7 @@ func (exec *BlockExecutor) verifySign(block *pb.Block) *pb.Block { for i, tx := range txs { go func(i int, tx *pb.Transaction) { defer wg.Done() - ok, _ := asym.Verify(crypto.Secp256k1, tx.Signature, tx.SignHash().Bytes(), tx.From) + ok, _ := asym.Verify(crypto.Secp256k1, tx.Signature, tx.SignHash().Bytes(), *tx.From) if !ok { mutex.Lock() defer mutex.Unlock() @@ -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 { @@ -254,22 +254,27 @@ func (exec *BlockExecutor) postBlockEvent(block *pb.Block, interchainMeta *pb.In } func (exec *BlockExecutor) applyTransaction(i int, tx *pb.Transaction, opt *agency.TxOpt) ([]byte, error) { - if tx.Data == nil { + if tx.Payload == nil { return nil, fmt.Errorf("empty transaction data") } - switch tx.Data.Type { + data := &pb.TransactionData{} + if err := data.Unmarshal(tx.Payload); err != nil { + return nil, err + } + + switch data.Type { case pb.TransactionData_NORMAL: - err := exec.transfer(tx.From, tx.To, tx.Data.Amount) + err := exec.transfer(tx.From, tx.To, data.Amount) return nil, err default: var instance vm.VM - switch tx.Data.VmType { + switch data.VmType { case pb.TransactionData_BVM: - ctx := vm.NewContext(tx, uint64(i), tx.Data, exec.ledger, exec.logger) + ctx := vm.NewContext(tx, uint64(i), data, exec.ledger, exec.logger) instance = boltvm.New(ctx, exec.validationEngine, exec.getContracts(opt)) case pb.TransactionData_XVM: - ctx := vm.NewContext(tx, uint64(i), tx.Data, exec.ledger, exec.logger) + ctx := vm.NewContext(tx, uint64(i), data, exec.ledger, exec.logger) imports, err := wasm.EmptyImports() if err != nil { return nil, err @@ -282,7 +287,7 @@ func (exec *BlockExecutor) applyTransaction(i int, tx *pb.Transaction, opt *agen return nil, fmt.Errorf("wrong vm type") } - return instance.Run(tx.Data.Payload) + return instance.Run(data.Payload) } } @@ -290,14 +295,14 @@ func (exec *BlockExecutor) clear() { exec.ledger.Clear() } -func (exec *BlockExecutor) transfer(from, to types.Address, value uint64) error { +func (exec *BlockExecutor) transfer(from, to *types.Address, value uint64) error { if value == 0 { return nil } 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) @@ -308,16 +313,16 @@ func (exec *BlockExecutor) transfer(from, to types.Address, value uint64) error return nil } -func (exec *BlockExecutor) calcReceiptMerkleRoot(receipts []*pb.Receipt) (types.Hash, error) { +func (exec *BlockExecutor) calcReceiptMerkleRoot(receipts []*pb.Receipt) (*types.Hash, error) { current := time.Now() receiptHashes := make([]merkletree.Content, 0, len(receipts)) for _, receipt := range receipts { - receiptHashes = append(receiptHashes, pb.TransactionHash(receipt.Hash().Bytes())) + receiptHashes = append(receiptHashes, receipt.Hash()) } receiptRoot, err := calcMerkleRoot(receiptHashes) if err != nil { - return types.Hash{}, err + return nil, err } exec.logger.WithField("time", time.Since(current)).Debug("Calculate receipt merkle roots") @@ -325,17 +330,17 @@ func (exec *BlockExecutor) calcReceiptMerkleRoot(receipts []*pb.Receipt) (types. return receiptRoot, nil } -func calcMerkleRoot(contents []merkletree.Content) (types.Hash, error) { +func calcMerkleRoot(contents []merkletree.Content) (*types.Hash, error) { if len(contents) == 0 { - return types.Hash{}, nil + return &types.Hash{}, nil } tree, err := merkletree.NewTree(contents) if err != nil { - return types.Hash{}, err + return nil, err } - return types.Bytes2Hash(tree.MerkleRoot()), nil + return types.NewHash(tree.MerkleRoot()), nil } func (exec *BlockExecutor) getContracts(opt *agency.TxOpt) map[string]agency.Contract { diff --git a/internal/executor/serial_executor.go b/internal/executor/serial_executor.go index d23fa54..3bfe678 100644 --- a/internal/executor/serial_executor.go +++ b/internal/executor/serial_executor.go @@ -7,7 +7,7 @@ import ( ) type SerialExecutor struct { - normalTxs []types.Hash + normalTxs []*types.Hash interchainCounter map[string][]uint64 applyTxFunc agency.ApplyTxFunc boltContracts map[string]agency.Contract @@ -26,7 +26,7 @@ func init() { func (se *SerialExecutor) ApplyTransactions(txs []*pb.Transaction) []*pb.Receipt { se.interchainCounter = make(map[string][]uint64) - se.normalTxs = make([]types.Hash, 0) + se.normalTxs = make([]*types.Hash, 0) receipts := make([]*pb.Receipt, 0, len(txs)) for i, tx := range txs { @@ -40,11 +40,11 @@ func (se *SerialExecutor) GetBoltContracts() map[string]agency.Contract { return se.boltContracts } -func (se *SerialExecutor) AddNormalTx(hash types.Hash) { +func (se *SerialExecutor) AddNormalTx(hash *types.Hash) { se.normalTxs = append(se.normalTxs, hash) } -func (se *SerialExecutor) GetNormalTxs() []types.Hash { +func (se *SerialExecutor) GetNormalTxs() []*types.Hash { return se.normalTxs } diff --git a/internal/ledger/account.go b/internal/ledger/account.go index 397ecf9..d410956 100644 --- a/internal/ledger/account.go +++ b/internal/ledger/account.go @@ -13,14 +13,14 @@ import ( ) type Account struct { - Addr types.Address + Addr *types.Address originAccount *innerAccount dirtyAccount *innerAccount originState sync.Map dirtyState sync.Map originCode []byte dirtyCode []byte - dirtyStateHash types.Hash + dirtyStateHash *types.Hash ldb storage.Storage cache *AccountCache lock sync.RWMutex @@ -32,7 +32,7 @@ type innerAccount struct { CodeHash []byte `json:"code_hash"` } -func newAccount(ldb storage.Storage, cache *AccountCache, addr types.Address) *Account { +func newAccount(ldb storage.Storage, cache *AccountCache, addr *types.Address) *Account { return &Account{ Addr: addr, ldb: ldb, @@ -254,7 +254,8 @@ func (o *Account) getStateJournalAndComputeHash() map[string][]byte { dirtyVal, _ := o.dirtyState.Load(key) dirtyStateData = append(dirtyStateData, dirtyVal.([]byte)...) } - o.dirtyStateHash = sha256.Sum256(dirtyStateData) + hash := sha256.Sum256(dirtyStateData) + o.dirtyStateHash = types.NewHash(hash[:]) return prevStates } @@ -272,7 +273,7 @@ func (o *Account) getDirtyData() []byte { dirtyData = append(dirtyData, data...) } - return append(dirtyData, o.dirtyStateHash[:]...) + return append(dirtyData, o.dirtyStateHash.Bytes()...) } func innerAccountChanged(account0 *innerAccount, account1 *innerAccount) bool { diff --git a/internal/ledger/account_cache.go b/internal/ledger/account_cache.go index a96bb0b..1daf5d2 100644 --- a/internal/ledger/account_cache.go +++ b/internal/ledger/account_cache.go @@ -10,9 +10,9 @@ import ( ) type AccountCache struct { - innerAccounts map[types.Address]*innerAccount - states map[types.Address]map[string][]byte - codes map[types.Address][]byte + innerAccounts map[string]*innerAccount + states map[string]map[string][]byte + codes map[string][]byte innerAccountCache *lru.Cache stateCache *lru.Cache codeCache *lru.Cache @@ -36,9 +36,9 @@ func NewAccountCache() (*AccountCache, error) { } return &AccountCache{ - innerAccounts: make(map[types.Address]*innerAccount), - states: make(map[types.Address]map[string][]byte), - codes: make(map[types.Address][]byte), + innerAccounts: make(map[string]*innerAccount), + states: make(map[string]map[string][]byte), + codes: make(map[string][]byte), innerAccountCache: innerAccountCache, stateCache: stateCache, codeCache: codeCache, @@ -46,7 +46,7 @@ func NewAccountCache() (*AccountCache, error) { }, nil } -func (ac *AccountCache) add(accounts map[types.Address]*Account) error { +func (ac *AccountCache) add(accounts map[string]*Account) error { ac.addToWriteBuffer(accounts) if err := ac.addToReadCache(accounts); err != nil { return err @@ -54,7 +54,7 @@ func (ac *AccountCache) add(accounts map[types.Address]*Account) error { return nil } -func (ac *AccountCache) addToReadCache(accounts map[types.Address]*Account) error { +func (ac *AccountCache) addToReadCache(accounts map[string]*Account) error { for addr, account := range accounts { var stateCache *lru.Cache @@ -86,7 +86,7 @@ func (ac *AccountCache) addToReadCache(accounts map[types.Address]*Account) erro return nil } -func (ac *AccountCache) addToWriteBuffer(accounts map[types.Address]*Account) { +func (ac *AccountCache) addToWriteBuffer(accounts map[string]*Account) { ac.rwLock.Lock() defer ac.rwLock.Unlock() @@ -112,7 +112,7 @@ func (ac *AccountCache) addToWriteBuffer(accounts map[types.Address]*Account) { } } -func (ac *AccountCache) remove(accounts map[types.Address]*Account) { +func (ac *AccountCache) remove(accounts map[string]*Account) { ac.rwLock.Lock() defer ac.rwLock.Unlock() @@ -147,16 +147,16 @@ func (ac *AccountCache) remove(accounts map[types.Address]*Account) { } } -func (ac *AccountCache) getInnerAccount(addr types.Address) (*innerAccount, bool) { - if ia, ok := ac.innerAccountCache.Get(addr); ok { +func (ac *AccountCache) getInnerAccount(addr *types.Address) (*innerAccount, bool) { + if ia, ok := ac.innerAccountCache.Get(addr.String()); ok { return ia.(*innerAccount), true } return nil, false } -func (ac *AccountCache) getState(addr types.Address, key string) ([]byte, bool) { - if value, ok := ac.stateCache.Get(addr); ok { +func (ac *AccountCache) getState(addr *types.Address, key string) ([]byte, bool) { + if value, ok := ac.stateCache.Get(addr.String()); ok { if val, ok := value.(*lru.Cache).Get(key); ok { return val.([]byte), true } @@ -165,21 +165,21 @@ func (ac *AccountCache) getState(addr types.Address, key string) ([]byte, bool) return nil, false } -func (ac *AccountCache) getCode(addr types.Address) ([]byte, bool) { - if code, ok := ac.codeCache.Get(addr); ok { +func (ac *AccountCache) getCode(addr *types.Address) ([]byte, bool) { + if code, ok := ac.codeCache.Get(addr.String()); ok { return code.([]byte), true } return nil, false } -func (ac *AccountCache) query(addr types.Address, prefix string) map[string][]byte { +func (ac *AccountCache) query(addr *types.Address, prefix string) map[string][]byte { ac.rwLock.RLock() defer ac.rwLock.RUnlock() ret := make(map[string][]byte) - if stateMap, ok := ac.states[addr]; ok { + if stateMap, ok := ac.states[addr.String()]; ok { for key, val := range stateMap { if strings.HasPrefix(key, prefix) { ret[key] = val @@ -193,9 +193,9 @@ func (ac *AccountCache) clear() { ac.rwLock.Lock() defer ac.rwLock.Unlock() - ac.innerAccounts = make(map[types.Address]*innerAccount) - ac.states = make(map[types.Address]map[string][]byte) - ac.codes = make(map[types.Address][]byte) + ac.innerAccounts = make(map[string]*innerAccount) + ac.states = make(map[string]map[string][]byte) + ac.codes = make(map[string][]byte) ac.innerAccountCache.Purge() ac.stateCache.Purge() ac.codeCache.Purge() diff --git a/internal/ledger/account_test.go b/internal/ledger/account_test.go index 2f9f1e3..e2ba5ad 100644 --- a/internal/ledger/account_test.go +++ b/internal/ledger/account_test.go @@ -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")) diff --git a/internal/ledger/blockchain.go b/internal/ledger/blockchain.go index 800d7ae..834b91c 100644 --- a/internal/ledger/blockchain.go +++ b/internal/ledger/blockchain.go @@ -39,7 +39,7 @@ func (l *ChainLedger) GetBlock(height uint64) (*pb.Block, error) { if txHashesData == nil { return nil, fmt.Errorf("cannot get tx hashes of block") } - txHashes := make([]types.Hash, 0) + txHashes := make([]*types.Hash, 0) if err := json.Unmarshal(txHashesData, &txHashes); err != nil { return nil, err } @@ -69,8 +69,8 @@ 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())) +func (l *ChainLedger) GetBlockByHash(hash *types.Hash) (*pb.Block, error) { + data := l.blockchainStore.Get(compositeKey(blockHashKey, hash.String())) if data == nil { return nil, storage.ErrorNotFound } @@ -84,8 +84,8 @@ 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())) +func (l *ChainLedger) GetTransaction(hash *types.Hash) (*pb.Transaction, error) { + v := l.blockchainStore.Get(compositeKey(transactionKey, hash.String())) if v == nil { return nil, storage.ErrorNotFound } @@ -111,8 +111,8 @@ 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())) +func (l *ChainLedger) GetTransactionMeta(hash *types.Hash) (*pb.TransactionMeta, error) { + data := l.blockchainStore.Get(compositeKey(transactionMetaKey, hash.String())) if data == nil { return nil, storage.ErrorNotFound } @@ -126,8 +126,8 @@ 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())) +func (l *ChainLedger) GetReceipt(hash *types.Hash) (*pb.Receipt, error) { + 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 @@ -291,7 +291,7 @@ func (l *ChainLedger) persistBlock(batcher storage.Batch, block *pb.Block) error var txHashes []types.Hash for _, tx := range block.Transactions { - txHashes = append(txHashes, tx.TransactionHash) + txHashes = append(txHashes, *tx.TransactionHash) } data, err := json.Marshal(txHashes) @@ -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 diff --git a/internal/ledger/chain_meta.go b/internal/ledger/chain_meta.go index d736200..bd54673 100644 --- a/internal/ledger/chain_meta.go +++ b/internal/ledger/chain_meta.go @@ -3,6 +3,8 @@ package ledger import ( "fmt" + "github.com/meshplus/bitxhub-kit/types" + "github.com/meshplus/bitxhub-kit/storage" "github.com/meshplus/bitxhub-model/pb" ) @@ -14,7 +16,11 @@ var ( func loadChainMeta(store storage.Storage) (*pb.ChainMeta, error) { ok := store.Has(chainKey) - chain := &pb.ChainMeta{} + chain := &pb.ChainMeta{ + Height: 0, + BlockHash: &types.Hash{}, + InterchainTxCount: 0, + } if ok { body := store.Get(chainKey) diff --git a/internal/ledger/genesis/genesis.go b/internal/ledger/genesis/genesis.go index 7c91aca..ab119e9 100644 --- a/internal/ledger/genesis/genesis.go +++ b/internal/ledger/genesis/genesis.go @@ -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) diff --git a/internal/ledger/journal.go b/internal/ledger/journal.go index a3b7d23..efd7d9e 100644 --- a/internal/ledger/journal.go +++ b/internal/ledger/journal.go @@ -14,7 +14,7 @@ var ( ) type journal struct { - Address types.Address + Address *types.Address PrevAccount *innerAccount AccountChanged bool PrevStates map[string][]byte @@ -24,7 +24,7 @@ type journal struct { type BlockJournal struct { Journals []*journal - ChangedHash types.Hash + ChangedHash *types.Hash } func (journal *journal) revert(batch storage.Batch) { diff --git a/internal/ledger/key.go b/internal/ledger/key.go index 5e2aa88..db11412 100644 --- a/internal/ledger/key.go +++ b/internal/ledger/key.go @@ -24,6 +24,6 @@ func compositeKey(prefix string, value interface{}) []byte { return append([]byte(prefix), []byte(fmt.Sprintf("%v", value))...) } -func composeStateKey(addr types.Address, key []byte) []byte { +func composeStateKey(addr *types.Address, key []byte) []byte { return append(addr.Bytes(), key...) } diff --git a/internal/ledger/ledger.go b/internal/ledger/ledger.go index 1ddeb3b..f1b6624 100644 --- a/internal/ledger/ledger.go +++ b/internal/ledger/ledger.go @@ -28,9 +28,9 @@ type ChainLedger struct { minJnlHeight uint64 maxJnlHeight uint64 events sync.Map - accounts map[types.Address]*Account + accounts map[string]*Account accountCache *AccountCache - prevJnlHash types.Hash + prevJnlHash *types.Hash repo *repo.Repo chainMutex sync.RWMutex @@ -43,7 +43,7 @@ type ChainLedger struct { type BlockData struct { Block *pb.Block Receipts []*pb.Receipt - Accounts map[types.Address]*Account + Accounts map[string]*Account Journal *BlockJournal InterchainMeta *pb.InterchainMeta } @@ -57,7 +57,7 @@ func New(repo *repo.Repo, blockchainStore storage.Storage, ldb storage.Storage, minJnlHeight, maxJnlHeight := getJournalRange(ldb) - prevJnlHash := types.Hash{} + prevJnlHash := &types.Hash{} if maxJnlHeight != 0 { blockJournal := getBlockJournal(maxJnlHeight, ldb) if blockJournal == nil { @@ -81,7 +81,7 @@ func New(repo *repo.Repo, blockchainStore storage.Storage, ldb storage.Storage, ldb: ldb, minJnlHeight: minJnlHeight, maxJnlHeight: maxJnlHeight, - accounts: make(map[types.Address]*Account), + accounts: make(map[string]*Account), accountCache: accountCache, prevJnlHash: prevJnlHash, } @@ -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) diff --git a/internal/ledger/ledger_test.go b/internal/ledger/ledger_test.go index 979455b..1b3494f 100644 --- a/internal/ledger/ledger_test.go +++ b/internal/ledger/ledger_test.go @@ -118,7 +118,7 @@ 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")) accounts, journal := ledger.FlushDirtyDataAndComputeJournal() @@ -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) @@ -173,10 +173,10 @@ func TestChainLedger_Commit(t *testing.T) { journal5 := getBlockJournal(maxHeight, ledger.ldb) assert.Equal(t, uint64(1), minHeight) assert.Equal(t, uint64(5), maxHeight) - assert.Equal(t, journal.ChangedHash, journal5.ChangedHash) + assert.Equal(t, journal.ChangedHash.String(), journal5.ChangedHash.String()) assert.Equal(t, 1, len(journal5.Journals)) entry := journal5.Journals[0] - assert.Equal(t, account, entry.Address) + assert.Equal(t, account.String(), entry.Address.String()) assert.True(t, entry.AccountChanged) assert.Equal(t, uint64(100), entry.PrevAccount.Balance) assert.Equal(t, uint64(0), entry.PrevAccount.Nonce) @@ -192,7 +192,7 @@ func TestChainLedger_Commit(t *testing.T) { // load ChainLedger from db, rollback to height 0 since no chain meta stored ldg, repoRoot := initLedger(t, repoRoot) assert.Equal(t, uint64(0), ldg.maxJnlHeight) - assert.Equal(t, types.Hash{}, ldg.prevJnlHash) + assert.Equal(t, &types.Hash{}, ldg.prevJnlHash) ok, _ := ldg.GetState(account, []byte("a")) assert.False(t, ok) @@ -214,11 +214,11 @@ 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) + assert.Equal(t, &hash0, ledger.prevJnlHash) ledger.SetBalance(addr0, 1) accounts, journal1 := ledger.FlushDirtyDataAndComputeJournal() @@ -288,7 +288,7 @@ func TestChainLedger_Rollback(t *testing.T) { assert.Equal(t, storage.ErrorNotFound, err) assert.Nil(t, block) assert.Equal(t, uint64(2), ledger.chainMeta.Height) - assert.Equal(t, journal2.ChangedHash, ledger.prevJnlHash) + assert.Equal(t, journal2.ChangedHash.String(), ledger.prevJnlHash.String()) assert.Equal(t, uint64(2), ledger.minJnlHeight) assert.Equal(t, uint64(2), ledger.maxJnlHeight) @@ -339,7 +339,7 @@ func TestChainLedger_RemoveJournalsBeforeBlock(t *testing.T) { journal = getBlockJournal(maxHeight, ledger.ldb) assert.Equal(t, uint64(1), minHeight) assert.Equal(t, uint64(4), maxHeight) - assert.Equal(t, journal4.ChangedHash, journal.ChangedHash) + assert.Equal(t, journal4.ChangedHash.String(), journal.ChangedHash.String()) err := ledger.RemoveJournalsBeforeBlock(5) assert.Equal(t, ErrorRemoveJournalOutOfRange, err) @@ -353,7 +353,7 @@ func TestChainLedger_RemoveJournalsBeforeBlock(t *testing.T) { journal = getBlockJournal(maxHeight, ledger.ldb) assert.Equal(t, uint64(2), minHeight) assert.Equal(t, uint64(4), maxHeight) - assert.Equal(t, journal4.ChangedHash, journal.ChangedHash) + assert.Equal(t, journal4.ChangedHash.String(), journal.ChangedHash.String()) err = ledger.RemoveJournalsBeforeBlock(2) assert.Nil(t, err) @@ -378,20 +378,20 @@ func TestChainLedger_RemoveJournalsBeforeBlock(t *testing.T) { journal = getBlockJournal(maxHeight, ledger.ldb) assert.Equal(t, uint64(4), minHeight) assert.Equal(t, uint64(4), maxHeight) - assert.Equal(t, journal4.ChangedHash, journal.ChangedHash) + assert.Equal(t, journal4.ChangedHash.String(), journal.ChangedHash.String()) ledger.Close() ledger, repoRoot = initLedger(t, repoRoot) assert.Equal(t, uint64(4), ledger.minJnlHeight) assert.Equal(t, uint64(4), ledger.maxJnlHeight) - assert.Equal(t, journal4.ChangedHash, ledger.prevJnlHash) + assert.Equal(t, journal4.ChangedHash.String(), ledger.prevJnlHash.String()) } 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]) @@ -675,14 +676,14 @@ func TestChainLedger_AddEvent(t *testing.T) { assert.Equal(t, 0, len(events)) } -func genBlockData(height uint64, accounts map[types.Address]*Account, journal *BlockJournal) *BlockData { +func genBlockData(height uint64, accounts map[string]*Account, journal *BlockJournal) *BlockData { return &BlockData{ Block: &pb.Block{ BlockHeader: &pb.BlockHeader{ Number: height, }, - BlockHash: sha256.Sum256([]byte{1}), - Transactions: []*pb.Transaction{{}}, + BlockHash: types.NewHash([]byte{1}), + Transactions: []*pb.Transaction{}, }, Receipts: nil, Accounts: accounts, @@ -705,7 +706,7 @@ BcNwjTDCxyxLNjFKQfMAc6sY6iJs+Ma59WZyC/4uhjE= return &repo.Repo{ Key: &repo.Key{ PrivKey: privKey, - Address: address.Hex(), + Address: address.String(), }, } } diff --git a/internal/ledger/state_accessor.go b/internal/ledger/state_accessor.go index bc73e42..5dae1ef 100644 --- a/internal/ledger/state_accessor.go +++ b/internal/ledger/state_accessor.go @@ -13,9 +13,9 @@ import ( var _ Ledger = (*ChainLedger)(nil) // GetOrCreateAccount get the account, if not exist, create a new account -func (l *ChainLedger) GetOrCreateAccount(addr types.Address) *Account { +func (l *ChainLedger) GetOrCreateAccount(addr *types.Address) *Account { l.lock.RLock() - value, ok := l.accounts[addr] + value, ok := l.accounts[addr.String()] l.lock.RUnlock() if ok { return value @@ -23,17 +23,17 @@ func (l *ChainLedger) GetOrCreateAccount(addr types.Address) *Account { l.lock.Lock() defer l.lock.Unlock() - if value, ok := l.accounts[addr]; ok { + if value, ok := l.accounts[addr.String()]; ok { return value } account := l.GetAccount(addr) - l.accounts[addr] = account + l.accounts[addr.String()] = account return account } // GetAccount get account info using account Address, if not found, create a new account -func (l *ChainLedger) GetAccount(address types.Address) *Account { +func (l *ChainLedger) GetAccount(address *types.Address) *Account { account := newAccount(l.ldb, l.accountCache, address) if innerAccount, ok := l.accountCache.getInnerAccount(address); ok { @@ -52,77 +52,77 @@ func (l *ChainLedger) GetAccount(address types.Address) *Account { } // GetBalanec get account balance using account Address -func (l *ChainLedger) GetBalance(addr types.Address) uint64 { +func (l *ChainLedger) GetBalance(addr *types.Address) uint64 { account := l.GetOrCreateAccount(addr) return account.GetBalance() } // SetBalance set account balance -func (l *ChainLedger) SetBalance(addr types.Address, value uint64) { +func (l *ChainLedger) SetBalance(addr *types.Address, value uint64) { account := l.GetOrCreateAccount(addr) account.SetBalance(value) } // GetState get account state value using account Address and key -func (l *ChainLedger) GetState(addr types.Address, key []byte) (bool, []byte) { +func (l *ChainLedger) GetState(addr *types.Address, key []byte) (bool, []byte) { account := l.GetOrCreateAccount(addr) return account.GetState(key) } // SetState set account state value using account Address and key -func (l *ChainLedger) SetState(addr types.Address, key []byte, v []byte) { +func (l *ChainLedger) SetState(addr *types.Address, key []byte, v []byte) { account := l.GetOrCreateAccount(addr) account.SetState(key, v) } // AddState add account state value using account Address and key -func (l *ChainLedger) AddState(addr types.Address, key []byte, v []byte) { +func (l *ChainLedger) AddState(addr *types.Address, key []byte, v []byte) { account := l.GetOrCreateAccount(addr) account.AddState(key, v) } // SetCode set contract code -func (l *ChainLedger) SetCode(addr types.Address, code []byte) { +func (l *ChainLedger) SetCode(addr *types.Address, code []byte) { account := l.GetOrCreateAccount(addr) account.SetCodeAndHash(code) } // GetCode get contract code -func (l *ChainLedger) GetCode(addr types.Address) []byte { +func (l *ChainLedger) GetCode(addr *types.Address) []byte { account := l.GetOrCreateAccount(addr) return account.Code() } // GetNonce get account nonce -func (l *ChainLedger) GetNonce(addr types.Address) uint64 { +func (l *ChainLedger) GetNonce(addr *types.Address) uint64 { account := l.GetOrCreateAccount(addr) return account.GetNonce() } // SetNonce set account nonce -func (l *ChainLedger) SetNonce(addr types.Address, nonce uint64) { +func (l *ChainLedger) SetNonce(addr *types.Address, nonce uint64) { account := l.GetOrCreateAccount(addr) account.SetNonce(nonce) } // QueryByPrefix query value using key -func (l *ChainLedger) QueryByPrefix(addr types.Address, prefix string) (bool, [][]byte) { +func (l *ChainLedger) QueryByPrefix(addr *types.Address, prefix string) (bool, [][]byte) { account := l.GetOrCreateAccount(addr) return account.Query(prefix) } func (l *ChainLedger) Clear() { l.events = sync.Map{} - l.accounts = make(map[types.Address]*Account) + l.accounts = make(map[string]*Account) } // FlushDirtyDataAndComputeJournal gets dirty accounts and computes block journal -func (l *ChainLedger) FlushDirtyDataAndComputeJournal() (map[types.Address]*Account, *BlockJournal) { - dirtyAccounts := make(map[types.Address]*Account) +func (l *ChainLedger) FlushDirtyDataAndComputeJournal() (map[string]*Account, *BlockJournal) { + dirtyAccounts := make(map[string]*Account) var dirtyAccountData []byte var journals []*journal - var sortedAddr []types.Address - accountData := make(map[types.Address][]byte) + var sortedAddr []string + accountData := make(map[string][]byte) for addr, account := range l.accounts { journal := account.getJournalIfModified() @@ -134,21 +134,19 @@ func (l *ChainLedger) FlushDirtyDataAndComputeJournal() (map[types.Address]*Acco } } - sort.Slice(sortedAddr, func(i, j int) bool { - return bytes.Compare(sortedAddr[i].Bytes(), sortedAddr[j].Bytes()) < 0 - }) + sort.Strings(sortedAddr) for _, addr := range sortedAddr { dirtyAccountData = append(dirtyAccountData, accountData[addr]...) } - dirtyAccountData = append(dirtyAccountData, l.prevJnlHash[:]...) + dirtyAccountData = append(dirtyAccountData, l.prevJnlHash.Bytes()...) journalHash := sha256.Sum256(dirtyAccountData) blockJournal := &BlockJournal{ Journals: journals, - ChangedHash: journalHash, + ChangedHash: types.NewHash(journalHash[:]), } - l.prevJnlHash = journalHash + l.prevJnlHash = blockJournal.ChangedHash l.Clear() l.accountCache.add(dirtyAccounts) @@ -156,7 +154,7 @@ func (l *ChainLedger) FlushDirtyDataAndComputeJournal() (map[types.Address]*Acco } // Commit commit the state -func (l *ChainLedger) Commit(height uint64, accounts map[types.Address]*Account, blockJournal *BlockJournal) error { +func (l *ChainLedger) Commit(height uint64, accounts map[string]*Account, blockJournal *BlockJournal) error { ldbBatch := l.ldb.NewBatch() for _, account := range accounts { @@ -271,7 +269,7 @@ func (l *ChainLedger) rollbackState(height uint64) error { journal := getBlockJournal(height, l.ldb) l.prevJnlHash = journal.ChangedHash } else { - l.prevJnlHash = types.Hash{} + l.prevJnlHash = &types.Hash{} l.minJnlHeight = 0 } l.maxJnlHeight = height diff --git a/internal/ledger/types.go b/internal/ledger/types.go index 7510535..eb3b2e3 100644 --- a/internal/ledger/types.go +++ b/internal/ledger/types.go @@ -34,46 +34,46 @@ type Ledger interface { // StateAccessor manipulates the state data type StateAccessor interface { // GetOrCreateAccount - GetOrCreateAccount(types.Address) *Account + GetOrCreateAccount(*types.Address) *Account // GetAccount - GetAccount(types.Address) *Account + GetAccount(*types.Address) *Account // GetBalance - GetBalance(types.Address) uint64 + GetBalance(*types.Address) uint64 // SetBalance - SetBalance(types.Address, uint64) + SetBalance(*types.Address, uint64) // GetState - GetState(types.Address, []byte) (bool, []byte) + GetState(*types.Address, []byte) (bool, []byte) // SetState - SetState(types.Address, []byte, []byte) + SetState(*types.Address, []byte, []byte) // AddState - AddState(types.Address, []byte, []byte) + AddState(*types.Address, []byte, []byte) // SetCode - SetCode(types.Address, []byte) + SetCode(*types.Address, []byte) // GetCode - GetCode(types.Address) []byte + GetCode(*types.Address) []byte // SetNonce - SetNonce(types.Address, uint64) + SetNonce(*types.Address, uint64) // GetNonce - GetNonce(types.Address) uint64 + GetNonce(*types.Address) uint64 // QueryByPrefix - QueryByPrefix(address types.Address, prefix string) (bool, [][]byte) + QueryByPrefix(address *types.Address, prefix string) (bool, [][]byte) // Commit commits the state data - Commit(height uint64, accounts map[types.Address]*Account, blockJournal *BlockJournal) error + Commit(height uint64, accounts map[string]*Account, blockJournal *BlockJournal) error // FlushDirtyDataAndComputeJournal flushes the dirty data and computes block journal - FlushDirtyDataAndComputeJournal() (map[types.Address]*Account, *BlockJournal) + FlushDirtyDataAndComputeJournal() (map[string]*Account, *BlockJournal) // Version Version() uint64 @@ -94,16 +94,16 @@ type BlockchainLedger interface { GetBlockSign(height uint64) ([]byte, error) // GetBlockByHash get the block using block hash - GetBlockByHash(hash types.Hash) (*pb.Block, error) + GetBlockByHash(hash *types.Hash) (*pb.Block, error) // GetTransaction get the transaction using transaction hash - GetTransaction(hash types.Hash) (*pb.Transaction, error) + GetTransaction(hash *types.Hash) (*pb.Transaction, error) // GetTransactionMeta get the transaction meta data - GetTransactionMeta(hash types.Hash) (*pb.TransactionMeta, error) + GetTransactionMeta(hash *types.Hash) (*pb.TransactionMeta, error) // GetReceipt get the transaction receipt - GetReceipt(hash types.Hash) (*pb.Receipt, error) + GetReceipt(hash *types.Hash) (*pb.Receipt, error) // GetInterchainMeta get interchain meta data GetInterchainMeta(height uint64) (*pb.InterchainMeta, error) diff --git a/internal/repo/key.go b/internal/repo/key.go index 1362392..40f980e 100644 --- a/internal/repo/key.go +++ b/internal/repo/key.go @@ -79,7 +79,7 @@ func loadPrivKey(repoRoot string) (*Key, error) { } return &Key{ - Address: address.Hex(), + Address: address.String(), PrivKey: privKey, Libp2pPrivKey: libp2pPrivKey, }, nil diff --git a/internal/router/interchain.go b/internal/router/interchain.go index 0e30efe..a3a8334 100644 --- a/internal/router/interchain.go +++ b/internal/router/interchain.go @@ -202,7 +202,7 @@ func (router *InterchainRouter) classify(block *pb.Block, meta *pb.InterchainMet var hashes []types.Hash for _, i := range vs.Slice { txs = append(txs, block.Transactions[i]) - hashes = append(hashes, block.Transactions[i].TransactionHash) + hashes = append(hashes, *block.Transactions[i].TransactionHash) } txsM[k] = txs hashesM[k] = hashes diff --git a/internal/router/interchain_test.go b/internal/router/interchain_test.go index 8d10a81..f35ebb4 100644 --- a/internal/router/interchain_test.go +++ b/internal/router/interchain_test.go @@ -105,10 +105,17 @@ func mockBlock(blockNumber uint64, txs []*pb.Transaction) *pb.Block { } func mockTx(data *pb.TransactionData) *pb.Transaction { - return &pb.Transaction{ - Data: data, - Nonce: uint64(rand.Int63()), + payload, err := data.Marshal() + if err != nil { + panic(err) } + tx := &pb.Transaction{ + Payload: payload, + Nonce: uint64(rand.Int63()), + } + tx.TransactionHash = tx.Hash() + + return tx } func mockTxData(t *testing.T, dataType pb.TransactionData_Type, vmType pb.TransactionData_VMType, ibtp proto.Marshaler) *pb.TransactionData { diff --git a/pkg/order/config.go b/pkg/order/config.go index 08591eb..66df92d 100644 --- a/pkg/order/config.go +++ b/pkg/order/config.go @@ -21,7 +21,7 @@ type Config struct { Nodes map[uint64]types.Address Applied uint64 Digest string - GetTransactionFunc func(hash types.Hash) (*pb.Transaction, error) + GetTransactionFunc func(hash *types.Hash) (*pb.Transaction, error) GetChainMetaFunc func() *pb.ChainMeta } type Option func(*Config) @@ -92,7 +92,7 @@ func WithGetChainMetaFunc(f func() *pb.ChainMeta) Option { } } -func WithGetTransactionFunc(f func(hash types.Hash) (*pb.Transaction, error)) Option { +func WithGetTransactionFunc(f func(hash *types.Hash) (*pb.Transaction, error)) Option { return func(config *Config) { config.GetTransactionFunc = f } diff --git a/pkg/order/etcdraft/node.go b/pkg/order/etcdraft/node.go index 54ddb93..b7b4cf2 100644 --- a/pkg/order/etcdraft/node.go +++ b/pkg/order/etcdraft/node.go @@ -168,7 +168,6 @@ func (n *Node) ReportState(height uint64, hash types.Hash) { if height%10 == 0 { n.logger.WithFields(logrus.Fields{ "height": height, - "hash": hash.ShortString(), }).Info("Report checkpoint") } appliedIndex, ok := n.blockAppliedIndex.Load(height) diff --git a/pkg/order/etcdraft/node_test.go b/pkg/order/etcdraft/node_test.go index 6cb2ae9..0c77179 100644 --- a/pkg/order/etcdraft/node_test.go +++ b/pkg/order/etcdraft/node_test.go @@ -40,8 +40,8 @@ func TestNode_Start(t *testing.T) { var ID uint64 = 1 nodes := make(map[uint64]types.Address) - nodes[ID] = types.String2Address("") - + hash := types.NewAddressByStr("000000000000000000000000000000000000000a") + nodes[ID] = *hash fileData, err := ioutil.ReadFile("../../../config/order.toml") require.Nil(t, err) err = ioutil.WriteFile(filepath.Join(repoRoot, "order.toml"), fileData, 0644) @@ -160,10 +160,7 @@ func generateTx() *pb.Transaction { tx := &pb.Transaction{ From: from, - To: types.String2Address(to), - Data: &pb.TransactionData{ - Amount: 10, - }, + To: types.NewAddressByStr(to), Timestamp: time.Now().UnixNano(), Nonce: 1, } @@ -277,7 +274,7 @@ func newSwarms(t *testing.T, peerCnt int) ([]*peermgr.Swarm, map[uint64]types.Ad address, err := privKeys[i].PublicKey().Address() require.Nil(t, err) - nodes[uint64(ID)] = address + nodes[uint64(ID)] = *address swarm, err := peermgr.New(repo, log.NewWithModule("p2p"), mockLedger) require.Nil(t, err) err = swarm.Start() @@ -285,4 +282,4 @@ func newSwarms(t *testing.T, peerCnt int) ([]*peermgr.Swarm, map[uint64]types.Ad swarms = append(swarms, swarm) } return swarms, nodes -} +} \ No newline at end of file diff --git a/pkg/order/etcdraft/proto/message.pb.go b/pkg/order/etcdraft/proto/message.pb.go index 6184e9f..7febd13 100644 --- a/pkg/order/etcdraft/proto/message.pb.go +++ b/pkg/order/etcdraft/proto/message.pb.go @@ -10,7 +10,6 @@ import ( github_com_meshplus_bitxhub_kit_types "github.com/meshplus/bitxhub-kit/types" io "io" math "math" - math_bits "math/bits" ) // Reference imports to suppress errors if they are not otherwise used. @@ -22,7 +21,7 @@ var _ = math.Inf // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package +const _ = proto.GoGoProtoPackageIsVersion2 // please upgrade the proto package type RaftMessage_Type int32 @@ -75,7 +74,7 @@ func (m *RaftMessage) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) return xxx_messageInfo_RaftMessage.Marshal(b, m, deterministic) } else { b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) + n, err := m.MarshalTo(b) if err != nil { return nil, err } @@ -116,7 +115,7 @@ func (m *RaftMessage) GetData() []byte { } type Ready struct { - TxHashes []github_com_meshplus_bitxhub_kit_types.Hash `protobuf:"bytes,1,rep,name=txHashes,proto3,customtype=github.com/meshplus/bitxhub-kit/types.Hash" json:"txHashes"` + TxHashes []github_com_meshplus_bitxhub_kit_types.Hash `protobuf:"bytes,1,rep,name=txHashes,proto3,customtype=github.com/meshplus/bitxhub-kit/types.Hash" json:"txHashes,omitempty"` Height uint64 `protobuf:"varint,2,opt,name=height,proto3" json:"height,omitempty"` } @@ -134,7 +133,7 @@ func (m *Ready) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_Ready.Marshal(b, m, deterministic) } else { b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) + n, err := m.MarshalTo(b) if err != nil { return nil, err } @@ -169,34 +168,33 @@ func init() { func init() { proto.RegisterFile("message.proto", fileDescriptor_33c57e4bae7b9afd) } var fileDescriptor_33c57e4bae7b9afd = []byte{ - // 321 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x4c, 0x90, 0xd1, 0x6a, 0xf2, 0x30, - 0x1c, 0xc5, 0x1b, 0xad, 0xf2, 0x7d, 0xff, 0xa9, 0x94, 0x5c, 0x6c, 0x65, 0x17, 0xb5, 0x78, 0x55, - 0x36, 0x6c, 0xc1, 0x3d, 0x81, 0x76, 0xb2, 0x8d, 0x31, 0x85, 0xd4, 0xc1, 0xee, 0xa4, 0x9d, 0xb1, - 0x29, 0x5b, 0x49, 0x31, 0x29, 0xe8, 0x5b, 0xec, 0x3d, 0xf6, 0x22, 0x5e, 0x7a, 0x39, 0x76, 0x21, - 0xc3, 0xbe, 0xc8, 0x68, 0xba, 0x0d, 0xaf, 0x72, 0x7e, 0xe1, 0x9c, 0x43, 0x4e, 0xa0, 0x9d, 0x52, - 0x21, 0xc2, 0x98, 0xba, 0xd9, 0x8a, 0x4b, 0x8e, 0x1b, 0xea, 0x38, 0xef, 0xc7, 0x89, 0x64, 0x79, - 0xe4, 0x3e, 0xf3, 0xd4, 0x8b, 0x79, 0xcc, 0x3d, 0x75, 0x1d, 0xe5, 0x4b, 0x45, 0x0a, 0x94, 0xaa, - 0x52, 0xbd, 0x77, 0x04, 0x27, 0x24, 0x5c, 0xca, 0x87, 0xaa, 0x0b, 0x5f, 0x82, 0x2e, 0x37, 0x19, - 0x35, 0x91, 0x8d, 0x9c, 0xce, 0xe0, 0xac, 0x72, 0xb9, 0x47, 0x0e, 0x77, 0xb6, 0xc9, 0x28, 0x51, - 0x26, 0x7c, 0x0a, 0xcd, 0xe5, 0x8a, 0xa7, 0x77, 0x0b, 0xb3, 0x66, 0x23, 0x47, 0x27, 0x3f, 0x84, - 0x31, 0xe8, 0x8b, 0x50, 0x86, 0x66, 0xdd, 0x46, 0x4e, 0x8b, 0x28, 0xdd, 0xf3, 0x41, 0x2f, 0x93, - 0xb8, 0x0d, 0xff, 0xfd, 0xe9, 0x24, 0x18, 0x4f, 0x82, 0xc7, 0xc0, 0xd0, 0xb0, 0x01, 0xad, 0x11, - 0x99, 0x0e, 0xaf, 0xfd, 0x61, 0x30, 0x9b, 0xcf, 0x9e, 0x0c, 0x84, 0x01, 0x9a, 0x37, 0x63, 0xa5, - 0x6b, 0xb8, 0x03, 0x50, 0xe9, 0xf9, 0xd0, 0xbf, 0x37, 0xea, 0x3d, 0x0e, 0x0d, 0x42, 0xc3, 0xc5, - 0x06, 0x4f, 0xe0, 0x9f, 0x5c, 0xdf, 0x86, 0x82, 0x51, 0x61, 0x22, 0xbb, 0xee, 0xb4, 0x46, 0x83, - 0xed, 0xbe, 0xab, 0x7d, 0xee, 0xbb, 0x17, 0x47, 0xfb, 0x53, 0x2a, 0x58, 0xf6, 0x9a, 0x0b, 0x2f, - 0x4a, 0xe4, 0x9a, 0xe5, 0x51, 0xff, 0x25, 0x91, 0x5e, 0xf9, 0x72, 0xe1, 0x96, 0x59, 0xf2, 0xd7, - 0x51, 0x2e, 0x61, 0x34, 0x89, 0x99, 0xfc, 0x5d, 0x52, 0xd1, 0xc8, 0xdc, 0x1e, 0x2c, 0xb4, 0x3b, - 0x58, 0xe8, 0xeb, 0x60, 0xa1, 0xb7, 0xc2, 0xd2, 0x76, 0x85, 0xa5, 0x7d, 0x14, 0x96, 0x16, 0x35, - 0xd5, 0xcf, 0x5c, 0x7d, 0x07, 0x00, 0x00, 0xff, 0xff, 0x4f, 0x14, 0xbe, 0x1f, 0x86, 0x01, 0x00, - 0x00, + // 318 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x4c, 0x90, 0xcf, 0x4a, 0xf3, 0x40, + 0x14, 0xc5, 0x33, 0x6d, 0x5a, 0xbe, 0xef, 0xda, 0x96, 0x30, 0x0b, 0x0d, 0x2e, 0x62, 0xe8, 0x2a, + 0x28, 0x4d, 0x40, 0x9f, 0xa0, 0x8d, 0xc5, 0x7f, 0xd8, 0xc2, 0xa4, 0x82, 0xbb, 0x32, 0xb1, 0xd3, + 0x4c, 0xa8, 0x61, 0x42, 0x67, 0x02, 0xed, 0x5b, 0xf8, 0x1e, 0xbe, 0x88, 0xcb, 0x2e, 0xc5, 0x85, + 0x48, 0xfb, 0x22, 0x92, 0x89, 0x4a, 0x57, 0x73, 0xce, 0x70, 0x7e, 0x97, 0x7b, 0x2e, 0xb4, 0x33, + 0x26, 0x25, 0x4d, 0x98, 0x9f, 0x2f, 0x85, 0x12, 0xb8, 0xa1, 0x9f, 0xe3, 0x5e, 0x92, 0x2a, 0x5e, + 0xc4, 0xfe, 0x93, 0xc8, 0x82, 0x44, 0x24, 0x22, 0xd0, 0xdf, 0x71, 0x31, 0xd7, 0x4e, 0x1b, 0xad, + 0x2a, 0xaa, 0xfb, 0x8a, 0xe0, 0x80, 0xd0, 0xb9, 0xba, 0xaf, 0x66, 0xe1, 0x33, 0x30, 0xd5, 0x3a, + 0x67, 0x36, 0x72, 0x91, 0xd7, 0x39, 0x3f, 0xaa, 0x52, 0xfe, 0x5e, 0xc2, 0x9f, 0xac, 0x73, 0x46, + 0x74, 0x08, 0x1f, 0x42, 0x73, 0xbe, 0x14, 0xd9, 0xcd, 0xcc, 0xae, 0xb9, 0xc8, 0x33, 0xc9, 0x8f, + 0xc3, 0x18, 0xcc, 0x19, 0x55, 0xd4, 0xae, 0xbb, 0xc8, 0x6b, 0x11, 0xad, 0xbb, 0x21, 0x98, 0x25, + 0x89, 0xdb, 0xf0, 0x3f, 0x1c, 0x8f, 0xa2, 0xe1, 0x28, 0x7a, 0x88, 0x2c, 0x03, 0x5b, 0xd0, 0x1a, + 0x90, 0x71, 0xff, 0x32, 0xec, 0x47, 0x93, 0xe9, 0xe4, 0xd1, 0x42, 0x18, 0xa0, 0x79, 0x35, 0xd4, + 0xba, 0x86, 0x3b, 0x00, 0x95, 0x9e, 0xf6, 0xc3, 0x3b, 0xab, 0xde, 0x5d, 0x40, 0x83, 0x30, 0x3a, + 0x5b, 0xe3, 0x5b, 0xf8, 0xa7, 0x56, 0xd7, 0x54, 0x72, 0x26, 0x6d, 0xe4, 0xd6, 0xbd, 0xd6, 0xc0, + 0xff, 0xf8, 0x3c, 0x39, 0xdd, 0xeb, 0x9e, 0x31, 0xc9, 0xf3, 0xe7, 0x42, 0x06, 0x71, 0xaa, 0x56, + 0xbc, 0x88, 0x7b, 0x8b, 0x54, 0x05, 0xe5, 0xd6, 0xd2, 0x2f, 0x39, 0xf2, 0xc7, 0x97, 0x2d, 0x38, + 0x4b, 0x13, 0xae, 0x7e, 0x5b, 0x54, 0x6e, 0x60, 0xbf, 0x6d, 0x1d, 0xb4, 0xd9, 0x3a, 0xe8, 0x6b, + 0xeb, 0xa0, 0x97, 0x9d, 0x63, 0x6c, 0x76, 0x8e, 0xf1, 0xbe, 0x73, 0x8c, 0xb8, 0xa9, 0xaf, 0x72, + 0xf1, 0x1d, 0x00, 0x00, 0xff, 0xff, 0xec, 0x5d, 0x36, 0x19, 0x82, 0x01, 0x00, 0x00, } func (m *RaftMessage) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) + n, err := m.MarshalTo(dAtA) if err != nil { return nil, err } @@ -204,39 +202,33 @@ func (m *RaftMessage) Marshal() (dAtA []byte, err error) { } func (m *RaftMessage) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *RaftMessage) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) + var i int _ = i var l int _ = l - if len(m.Data) > 0 { - i -= len(m.Data) - copy(dAtA[i:], m.Data) - i = encodeVarintMessage(dAtA, i, uint64(len(m.Data))) - i-- - dAtA[i] = 0x1a + if m.Type != 0 { + dAtA[i] = 0x8 + i++ + i = encodeVarintMessage(dAtA, i, uint64(m.Type)) } if m.FromId != 0 { - i = encodeVarintMessage(dAtA, i, uint64(m.FromId)) - i-- dAtA[i] = 0x10 + i++ + i = encodeVarintMessage(dAtA, i, uint64(m.FromId)) } - if m.Type != 0 { - i = encodeVarintMessage(dAtA, i, uint64(m.Type)) - i-- - dAtA[i] = 0x8 + if len(m.Data) > 0 { + dAtA[i] = 0x1a + i++ + i = encodeVarintMessage(dAtA, i, uint64(len(m.Data))) + i += copy(dAtA[i:], m.Data) } - return len(dAtA) - i, nil + return i, nil } func (m *Ready) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) + n, err := m.MarshalTo(dAtA) if err != nil { return nil, err } @@ -244,47 +236,38 @@ func (m *Ready) Marshal() (dAtA []byte, err error) { } func (m *Ready) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *Ready) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) + var i int _ = i var l int _ = l - if m.Height != 0 { - i = encodeVarintMessage(dAtA, i, uint64(m.Height)) - i-- - dAtA[i] = 0x10 - } if len(m.TxHashes) > 0 { - for iNdEx := len(m.TxHashes) - 1; iNdEx >= 0; iNdEx-- { - { - size := m.TxHashes[iNdEx].Size() - i -= size - if _, err := m.TxHashes[iNdEx].MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- + for _, msg := range m.TxHashes { dAtA[i] = 0xa + i++ + i = encodeVarintMessage(dAtA, i, uint64(msg.Size())) + n, err := msg.MarshalTo(dAtA[i:]) + if err != nil { + return 0, err + } + i += n } } - return len(dAtA) - i, nil + if m.Height != 0 { + dAtA[i] = 0x10 + i++ + i = encodeVarintMessage(dAtA, i, uint64(m.Height)) + } + return i, nil } func encodeVarintMessage(dAtA []byte, offset int, v uint64) int { - offset -= sovMessage(v) - base := offset for v >= 1<<7 { dAtA[offset] = uint8(v&0x7f | 0x80) v >>= 7 offset++ } dAtA[offset] = uint8(v) - return base + return offset + 1 } func (m *RaftMessage) Size() (n int) { if m == nil { @@ -324,7 +307,14 @@ func (m *Ready) Size() (n int) { } func sovMessage(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 + for { + n++ + x >>= 7 + if x == 0 { + break + } + } + return n } func sozMessage(x uint64) (n int) { return sovMessage(uint64((x << 1) ^ uint64((int64(x) >> 63)))) @@ -564,7 +554,6 @@ func (m *Ready) Unmarshal(dAtA []byte) error { func skipMessage(dAtA []byte) (n int, err error) { l := len(dAtA) iNdEx := 0 - depth := 0 for iNdEx < l { var wire uint64 for shift := uint(0); ; shift += 7 { @@ -596,8 +585,10 @@ func skipMessage(dAtA []byte) (n int, err error) { break } } + return iNdEx, nil case 1: iNdEx += 8 + return iNdEx, nil case 2: var length int for shift := uint(0); ; shift += 7 { @@ -618,30 +609,55 @@ func skipMessage(dAtA []byte) (n int, err error) { return 0, ErrInvalidLengthMessage } iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupMessage + if iNdEx < 0 { + return 0, ErrInvalidLengthMessage } - depth-- + return iNdEx, nil + case 3: + for { + var innerWire uint64 + var start int = iNdEx + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowMessage + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + innerWire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + innerWireType := int(innerWire & 0x7) + if innerWireType == 4 { + break + } + next, err := skipMessage(dAtA[start:]) + if err != nil { + return 0, err + } + iNdEx = start + next + if iNdEx < 0 { + return 0, ErrInvalidLengthMessage + } + } + return iNdEx, nil + case 4: + return iNdEx, nil case 5: iNdEx += 4 + return iNdEx, nil default: return 0, fmt.Errorf("proto: illegal wireType %d", wireType) } - if iNdEx < 0 { - return 0, ErrInvalidLengthMessage - } - if depth == 0 { - return iNdEx, nil - } } - return 0, io.ErrUnexpectedEOF + panic("unreachable") } var ( - ErrInvalidLengthMessage = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowMessage = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupMessage = fmt.Errorf("proto: unexpected end of group") + ErrInvalidLengthMessage = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowMessage = fmt.Errorf("proto: integer overflow") ) diff --git a/pkg/order/etcdraft/proto/message.proto b/pkg/order/etcdraft/proto/message.proto index 5c22d98..b4d7ad2 100644 --- a/pkg/order/etcdraft/proto/message.proto +++ b/pkg/order/etcdraft/proto/message.proto @@ -16,6 +16,6 @@ message RaftMessage { } message Ready { - repeated bytes txHashes = 1 [(gogoproto.customtype) = "github.com/meshplus/bitxhub-kit/types.Hash", (gogoproto.nullable) = false]; + repeated bytes txHashes = 1 [(gogoproto.customtype) = "github.com/meshplus/bitxhub-kit/types.Hash"]; uint64 height = 2; } \ No newline at end of file diff --git a/pkg/order/mempool/mempool_impl.go b/pkg/order/mempool/mempool_impl.go index f4bded6..45a471f 100644 --- a/pkg/order/mempool/mempool_impl.go +++ b/pkg/order/mempool/mempool_impl.go @@ -32,7 +32,7 @@ type mempoolImpl struct { storage storage.Storage peerMgr peermgr.PeerManager //network manager batchTimerMgr *timerManager - ledgerHelper func(hash types.Hash) (*pb.Transaction, error) + ledgerHelper func(hash *types.Hash) (*pb.Transaction, error) } func newMempoolImpl(config *Config, storage storage.Storage, batchC chan *raftproto.Ready) *mempoolImpl { @@ -155,18 +155,14 @@ func (mpi *mempoolImpl) processTransactions(txs []*pb.Transaction) error { validTxs := make(map[string][]*pb.Transaction) for _, tx := range txs { // check the sequence number of tx - txAccount, err := getAccount(tx) - if err != nil { - mpi.logger.Warningf("get tx account failed, err: %s", err.Error()) - continue - } + txAccount := tx.Account() currentSeqNo := mpi.txStore.nonceCache.getPendingNonce(txAccount) if tx.Nonce < currentSeqNo { mpi.logger.Warningf("Account %s, current sequence number is %d, required %d", txAccount, tx.Nonce, currentSeqNo+1) continue } // check the existence of hash of this tx - txHash := tx.TransactionHash.Hex() + txHash := tx.TransactionHash.String() if txPointer := mpi.txStore.txHashMap[txHash]; txPointer != nil { mpi.logger.Warningf("Tx %s already received", txHash) continue @@ -208,7 +204,7 @@ func (txStore *transactionStore) InsertTxs(txs map[string][]*pb.Transaction) map dirtyAccounts := make(map[string]bool) for account, list := range txs { for _, tx := range list { - txHash := tx.TransactionHash.Hex() + txHash := tx.TransactionHash.String() txPointer := &orderedIndexKey{ account: account, nonce: tx.Nonce, @@ -296,7 +292,7 @@ func (mpi *mempoolImpl) generateBlock(isTimeout bool) (*raftproto.Ready, error) txList := make([]*pb.Transaction, len(result)) for i, v := range result { rawTransaction := mpi.txStore.getTxByOrderKey(v.account, v.nonce) - hashList[i] = rawTransaction.TransactionHash + hashList[i] = *rawTransaction.TransactionHash txList[i] = rawTransaction } mpi.increaseBatchSeqNo() @@ -327,7 +323,7 @@ func (mpi *mempoolImpl) getBlock(ready *raftproto.Ready) *mempoolBatch { mpi.logger.Warningf("Leader get block failed, can't find block %d from batchedCache", ready.Height) missingTxnHashList := make(map[uint64]string) for i, txHash := range ready.TxHashes { - missingTxnHashList[uint64(i)] = txHash.Hex() + missingTxnHashList[uint64(i)] = txHash.String() } res.missingTxnHashList = missingTxnHashList } else { @@ -358,18 +354,19 @@ func (mpi *mempoolImpl) constructSameBatch(ready *raftproto.Ready) *mempoolBatch txItem *txItem ok bool ) - if txPointer, _ = mpi.txStore.txHashMap[txHash.Hex()]; txPointer == nil { - missingTxList[uint64(index)] = txHash.Hex() + strHash := txHash.String() + if txPointer, _ = mpi.txStore.txHashMap[strHash]; txPointer == nil { + missingTxList[uint64(index)] = strHash continue } if txMap, ok = mpi.txStore.allTxs[txPointer.account]; !ok { - mpi.logger.Warningf("Transaction %s exist in txHashMap but not in allTxs", txHash.Hex()) - missingTxList[uint64(index)] = txHash.Hex() + mpi.logger.Warningf("Transaction %s exist in txHashMap but not in allTxs", strHash) + missingTxList[uint64(index)] = strHash continue } if txItem, ok = txMap.items[txPointer.nonce]; !ok { - mpi.logger.Warningf("Transaction %s exist in txHashMap but not in allTxs", txHash.Hex()) - missingTxList[uint64(index)] = txHash.Hex() + mpi.logger.Warningf("Transaction %s exist in txHashMap but not in allTxs", strHash) + missingTxList[uint64(index)] = strHash continue } txList = append(txList, txItem.tx) @@ -390,11 +387,11 @@ func (mpi *mempoolImpl) processCommitTransactions(ready *raftproto.Ready) { dirtyAccounts := make(map[string]bool) // update current cached commit nonce for account for _, txHash := range ready.TxHashes { - txHashStr := txHash.Hex() - txPointer := mpi.txStore.txHashMap[txHashStr] - txPointer, ok := mpi.txStore.txHashMap[txHashStr] + strHash := txHash.String() + txPointer := mpi.txStore.txHashMap[strHash] + txPointer, ok := mpi.txStore.txHashMap[strHash] if !ok { - mpi.logger.Warningf("Remove transaction %s failed, Can't find it from txHashMap", txHashStr) + mpi.logger.Warningf("Remove transaction %s failed, Can't find it from txHashMap", strHash) continue } preCommitNonce := mpi.txStore.nonceCache.getCommitNonce(txPointer.account) @@ -402,7 +399,7 @@ func (mpi *mempoolImpl) processCommitTransactions(ready *raftproto.Ready) { if preCommitNonce < newCommitNonce { mpi.txStore.nonceCache.setCommitNonce(txPointer.account, newCommitNonce) } - delete(mpi.txStore.txHashMap, txHashStr) + delete(mpi.txStore.txHashMap, strHash) delete(mpi.txStore.batchedTxs, *txPointer) dirtyAccounts[txPointer.account] = true } @@ -508,7 +505,7 @@ func (mpi *mempoolImpl) loadTxnFromCache(fetchTxnRequest *FetchTxnRequest) (map[ targetBatchLen := uint64(len(targetBatch)) txList := make(map[uint64]*pb.Transaction, len(missingHashList)) for index, txHash := range missingHashList { - if index > targetBatchLen || targetBatch[index].TransactionHash.Hex() != txHash { + if index > targetBatchLen || targetBatch[index].TransactionHash.String() != txHash { return nil, fmt.Errorf("find invaild transaction, index: %d, targetHash: %s", index, txHash) } txList[index] = targetBatch[index] @@ -523,11 +520,11 @@ func (mpi *mempoolImpl) loadTxnFromStorage(fetchTxnRequest *FetchTxnRequest) (ma for index, txHash := range missingHashList { var ( tx *pb.Transaction - rawHash types.Hash + rawHash []byte err error ok bool ) - if rawHash, err = hex2Hash(txHash); err != nil { + if rawHash, err = types.HexDecodeString(txHash); err != nil { return nil, err } if tx, ok = mpi.load(rawHash); !ok { @@ -544,14 +541,14 @@ func (mpi *mempoolImpl) loadTxnFromLedger(fetchTxnRequest *FetchTxnRequest) (map txList := make(map[uint64]*pb.Transaction) for index, txHash := range missingHashList { var ( - tx *pb.Transaction - rawHash types.Hash - err error + tx *pb.Transaction + err error ) - if rawHash, err = hex2Hash(txHash); err != nil { - return nil, err + hash := types.NewHashByStr(txHash) + if hash == nil { + return nil, errors.New("nil hash") } - if tx, err = mpi.ledgerHelper(rawHash); err != nil { + if tx, err = mpi.ledgerHelper(hash); err != nil { return nil, err } txList[index] = tx @@ -572,7 +569,7 @@ func (mpi *mempoolImpl) processFetchTxnResponse(fetchTxnResponse *FetchTxnRespon validTxn := make([]*pb.Transaction, 0) targetBatch := mpi.txStore.missingBatch[fetchTxnResponse.Height] for index, tx := range fetchTxnResponse.MissingTxnList { - if tx.Hash().Hex() != targetBatch[index] { + if tx.TransactionHash.String() != targetBatch[index] { return errors.New("find a hash mismatch tx") } validTxn = append(validTxn, tx) diff --git a/pkg/order/mempool/mempool_impl_test.go b/pkg/order/mempool/mempool_impl_test.go index 771d3c7..288e30c 100644 --- a/pkg/order/mempool/mempool_impl_test.go +++ b/pkg/order/mempool/mempool_impl_test.go @@ -30,12 +30,12 @@ func TestProcessTransactions(t *testing.T) { ast.Equal(1, mpi.txStore.parkingLotIndex.size()) ast.Equal(5, len(mpi.txStore.txHashMap)) ast.Equal(0, len(mpi.txStore.batchedCache)) - ast.Equal(2, mpi.txStore.allTxs[account1.Hex()].index.size()) - ast.Equal(3, mpi.txStore.allTxs[account2.Hex()].index.size()) - ast.Equal(uint64(1), mpi.txStore.nonceCache.getCommitNonce(account1.Hex())) - ast.Equal(uint64(3), mpi.txStore.nonceCache.getPendingNonce(account1.Hex())) - ast.Equal(uint64(1), mpi.txStore.nonceCache.getCommitNonce(account2.Hex())) - ast.Equal(uint64(3), mpi.txStore.nonceCache.getPendingNonce(account2.Hex())) + ast.Equal(2, mpi.txStore.allTxs[account1.String()].index.size()) + ast.Equal(3, mpi.txStore.allTxs[account2.String()].index.size()) + ast.Equal(uint64(1), mpi.txStore.nonceCache.getCommitNonce(account1.String())) + ast.Equal(uint64(3), mpi.txStore.nonceCache.getPendingNonce(account1.String())) + ast.Equal(uint64(1), mpi.txStore.nonceCache.getCommitNonce(account2.String())) + ast.Equal(uint64(3), mpi.txStore.nonceCache.getPendingNonce(account2.String())) go func() { mpi.batchSize = 4 @@ -57,10 +57,10 @@ func TestProcessTransactions(t *testing.T) { ast.Equal(7, len(mpi.txStore.txHashMap)) ast.Equal(1, len(mpi.txStore.batchedCache)) ast.Equal(4, len(mpi.txStore.batchedCache[uint64(2)])) - ast.Equal(3, mpi.txStore.allTxs[account1.Hex()].index.size()) - ast.Equal(4, mpi.txStore.allTxs[account2.Hex()].index.size()) - ast.Equal(uint64(4), mpi.txStore.nonceCache.getPendingNonce(account1.Hex())) - ast.Equal(uint64(3), mpi.txStore.nonceCache.getPendingNonce(account2.Hex())) + ast.Equal(3, mpi.txStore.allTxs[account1.String()].index.size()) + ast.Equal(4, mpi.txStore.allTxs[account2.String()].index.size()) + ast.Equal(uint64(4), mpi.txStore.nonceCache.getPendingNonce(account1.String())) + ast.Equal(uint64(3), mpi.txStore.nonceCache.getPendingNonce(account2.String())) } } @@ -75,7 +75,7 @@ func TestProcessFetchTxnRequest(t *testing.T) { txList = append(txList, tx1) missingList := make(map[uint64]string) - missingList[0] = tx1.TransactionHash.Hex() + missingList[0] = tx1.TransactionHash.String() fetchTxnRequest := &FetchTxnRequest{ Height: uint64(2), MissingTxHashes: missingList, @@ -105,7 +105,7 @@ func TestProcessFetchTxnResponse(t *testing.T) { privKey1 := genPrivKey() tx1 := constructTx(uint64(1), &privKey1) missingList := make(map[uint64]string) - missingList[0] = tx1.TransactionHash.Hex() + missingList[0] = tx1.TransactionHash.String() mpi.txStore.missingBatch[uint64(2)] = missingList fetchTxnResponse.MissingTxnList = make(map[uint64]*pb.Transaction) diff --git a/pkg/order/mempool/mempool_test.go b/pkg/order/mempool/mempool_test.go index a874dfd..28f7f4d 100644 --- a/pkg/order/mempool/mempool_test.go +++ b/pkg/order/mempool/mempool_test.go @@ -104,7 +104,7 @@ func TestGetBlock(t *testing.T) { var txList []*pb.Transaction var txHashList []types.Hash txList = append(txList, tx1, tx2, tx3, tx4) - txHashList = append(txHashList, tx1.TransactionHash, tx2.TransactionHash, tx3.TransactionHash, tx5.TransactionHash) + txHashList = append(txHashList, *tx1.TransactionHash, *tx2.TransactionHash, *tx3.TransactionHash, *tx5.TransactionHash) err = mpi.processTransactions(txList) ast.Nil(err) ready := &raftproto.Ready{ @@ -146,7 +146,7 @@ func TestGetPendingNonceByAccount(t *testing.T) { privKey1 := genPrivKey() account1, _ := privKey1.PublicKey().Address() - nonce := mpi.GetPendingNonceByAccount(account1.Hex()) + nonce := mpi.GetPendingNonceByAccount(account1.String()) ast.Equal(uint64(1), nonce) privKey2 := genPrivKey() @@ -160,9 +160,9 @@ func TestGetPendingNonceByAccount(t *testing.T) { txList = append(txList, tx1, tx2, tx3, tx4, tx5) err = mpi.processTransactions(txList) ast.Nil(err) - nonce = mpi.GetPendingNonceByAccount(account1.Hex()) + nonce = mpi.GetPendingNonceByAccount(account1.String()) ast.Equal(uint64(3), nonce) - nonce = mpi.GetPendingNonceByAccount(account2.Hex()) + nonce = mpi.GetPendingNonceByAccount(account2.String()) ast.Equal(uint64(3), nonce, "not 4") } @@ -175,7 +175,7 @@ func TestCommitTransactions(t *testing.T) { privKey1 := genPrivKey() account1, _ := privKey1.PublicKey().Address() - nonce := mpi.GetPendingNonceByAccount(account1.Hex()) + nonce := mpi.GetPendingNonceByAccount(account1.String()) ast.Equal(uint64(1), nonce) privKey2 := genPrivKey() @@ -205,7 +205,7 @@ func TestCommitTransactions(t *testing.T) { ast.Equal(uint64(2), height) var txHashList []types.Hash - txHashList = append(txHashList, tx1.TransactionHash, tx2.TransactionHash, tx3.TransactionHash, tx5.TransactionHash) + txHashList = append(txHashList, *tx1.TransactionHash, *tx2.TransactionHash, *tx3.TransactionHash, *tx5.TransactionHash) ready := &raftproto.Ready{ Height: uint64(2), TxHashes: txHashList, diff --git a/pkg/order/mempool/mempool_test_util.go b/pkg/order/mempool/mempool_test_util.go index fd87de9..008ab47 100644 --- a/pkg/order/mempool/mempool_test_util.go +++ b/pkg/order/mempool/mempool_test_util.go @@ -2,7 +2,9 @@ package mempool import ( "encoding/json" + "errors" "fmt" + "math/rand" "os" "time" @@ -22,7 +24,7 @@ import ( ) var ( - InterchainContractAddr = types.String2Address("000000000000000000000000000000000000000a") + InterchainContractAddr = types.NewAddressByStr("000000000000000000000000000000000000000a") ) const ( @@ -43,6 +45,7 @@ func mockMempoolImpl() (*mempoolImpl, chan *raftproto.Ready) { FetchTimeout: DefaultFetchTxnTimeout, TxSliceTimeout: DefaultTxSetTick, Logger: log.NewWithModule("consensus"), + GetTransactionFunc:getTransactionFunc, } config.PeerMgr = newMockPeerMgr() db, _ := leveldb.New(LevelDBDir) @@ -51,6 +54,10 @@ func mockMempoolImpl() (*mempoolImpl, chan *raftproto.Ready) { return mempool, proposalC } +func getTransactionFunc(hash *types.Hash) (*pb.Transaction, error) { + return nil,errors.New("can't find transaction") +} + func genPrivKey() crypto.PrivateKey { privKey, _ := asym.GenerateKeyPair(crypto.Secp256k1) return privKey @@ -81,9 +88,14 @@ func constructIBTPTx(nonce uint64, privKey *crypto.PrivateKey) *pb.Transaction { privK = *privKey pubKey := privK.PublicKey() from, _ := pubKey.Address() - to := from.Hex() - ibtp := mockIBTP(from.Hex(), to, nonce) - tx := mockInterChainTx(ibtp) + to := from.String() + ibtp := mockIBTP(from.String(), to, nonce) + tx := &pb.Transaction{ + To: InterchainContractAddr, + Nonce: ibtp.Index, + IBTP: ibtp, + Extra: []byte(fmt.Sprintf("%s-%s-%d", ibtp.From, ibtp.To, ibtp.Type)), + } tx.Timestamp = time.Now().UnixNano() sig, _ := privK.Sign(tx.SignHash().Bytes()) tx.Signature = sig @@ -99,26 +111,6 @@ func cleanTestData() bool { return true } -func mockInterChainTx(ibtp *pb.IBTP) *pb.Transaction { - ib, _ := ibtp.Marshal() - ipd := &pb.InvokePayload{ - Method: "HandleIBTP", - Args: []*pb.Arg{{Value: ib}}, - } - pd, _ := ipd.Marshal() - data := &pb.TransactionData{ - VmType: pb.TransactionData_BVM, - Type: pb.TransactionData_INVOKE, - Payload: pd, - } - return &pb.Transaction{ - To: InterchainContractAddr, - Nonce: ibtp.Index, - Data: data, - Extra: []byte(fmt.Sprintf("%s-%s-%d", ibtp.From, ibtp.To, ibtp.Type)), - } -} - func mockIBTP(from, to string, nonce uint64) *pb.IBTP { content := pb.Content{ SrcContractId: from, @@ -141,6 +133,12 @@ func mockIBTP(from, to string, nonce uint64) *pb.IBTP { } } +func newHash(hash string) *types.Hash { + hashBytes := make([]byte,types.HashLength) + rand.Read(hashBytes) + return types.NewHash(hashBytes) +} + type mockPeerMgr struct { mock.Mock EventChan chan *pb.Message diff --git a/pkg/order/mempool/message.pb.go b/pkg/order/mempool/message.pb.go index b945147..6c32378 100644 --- a/pkg/order/mempool/message.pb.go +++ b/pkg/order/mempool/message.pb.go @@ -9,7 +9,6 @@ import ( pb "github.com/meshplus/bitxhub-model/pb" io "io" math "math" - math_bits "math/bits" ) // Reference imports to suppress errors if they are not otherwise used. @@ -21,7 +20,7 @@ var _ = math.Inf // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package +const _ = proto.GoGoProtoPackageIsVersion2 // please upgrade the proto package type TxSlice struct { TxList []*pb.Transaction `protobuf:"bytes,1,rep,name=TxList,proto3" json:"TxList,omitempty"` @@ -41,7 +40,7 @@ func (m *TxSlice) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_TxSlice.Marshal(b, m, deterministic) } else { b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) + n, err := m.MarshalTo(b) if err != nil { return nil, err } @@ -87,7 +86,7 @@ func (m *FetchTxnRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, err return xxx_messageInfo_FetchTxnRequest.Marshal(b, m, deterministic) } else { b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) + n, err := m.MarshalTo(b) if err != nil { return nil, err } @@ -147,7 +146,7 @@ func (m *FetchTxnResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, er return xxx_messageInfo_FetchTxnResponse.Marshal(b, m, deterministic) } else { b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) + n, err := m.MarshalTo(b) if err != nil { return nil, err } @@ -228,7 +227,7 @@ var fileDescriptor_33c57e4bae7b9afd = []byte{ func (m *TxSlice) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) + n, err := m.MarshalTo(dAtA) if err != nil { return nil, err } @@ -236,36 +235,29 @@ func (m *TxSlice) Marshal() (dAtA []byte, err error) { } func (m *TxSlice) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *TxSlice) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) + var i int _ = i var l int _ = l if len(m.TxList) > 0 { - for iNdEx := len(m.TxList) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.TxList[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- + for _, msg := range m.TxList { dAtA[i] = 0xa + i++ + i = encodeVarintMessage(dAtA, i, uint64(msg.Size())) + n, err := msg.MarshalTo(dAtA[i:]) + if err != nil { + return 0, err + } + i += n } } - return len(dAtA) - i, nil + return i, nil } func (m *FetchTxnRequest) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) + n, err := m.MarshalTo(dAtA) if err != nil { return nil, err } @@ -273,49 +265,43 @@ func (m *FetchTxnRequest) Marshal() (dAtA []byte, err error) { } func (m *FetchTxnRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *FetchTxnRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) + var i int _ = i var l int _ = l - if len(m.MissingTxHashes) > 0 { - for k := range m.MissingTxHashes { - v := m.MissingTxHashes[k] - baseI := i - i -= len(v) - copy(dAtA[i:], v) - i = encodeVarintMessage(dAtA, i, uint64(len(v))) - i-- - dAtA[i] = 0x12 - i = encodeVarintMessage(dAtA, i, uint64(k)) - i-- - dAtA[i] = 0x8 - i = encodeVarintMessage(dAtA, i, uint64(baseI-i)) - i-- - dAtA[i] = 0x1a - } + if m.ReplicaId != 0 { + dAtA[i] = 0x8 + i++ + i = encodeVarintMessage(dAtA, i, uint64(m.ReplicaId)) } if m.Height != 0 { - i = encodeVarintMessage(dAtA, i, uint64(m.Height)) - i-- dAtA[i] = 0x10 + i++ + i = encodeVarintMessage(dAtA, i, uint64(m.Height)) } - if m.ReplicaId != 0 { - i = encodeVarintMessage(dAtA, i, uint64(m.ReplicaId)) - i-- - dAtA[i] = 0x8 + if len(m.MissingTxHashes) > 0 { + for k, _ := range m.MissingTxHashes { + dAtA[i] = 0x1a + i++ + v := m.MissingTxHashes[k] + mapSize := 1 + sovMessage(uint64(k)) + 1 + len(v) + sovMessage(uint64(len(v))) + i = encodeVarintMessage(dAtA, i, uint64(mapSize)) + dAtA[i] = 0x8 + i++ + i = encodeVarintMessage(dAtA, i, uint64(k)) + dAtA[i] = 0x12 + i++ + i = encodeVarintMessage(dAtA, i, uint64(len(v))) + i += copy(dAtA[i:], v) + } } - return len(dAtA) - i, nil + return i, nil } func (m *FetchTxnResponse) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) + n, err := m.MarshalTo(dAtA) if err != nil { return nil, err } @@ -323,62 +309,58 @@ func (m *FetchTxnResponse) Marshal() (dAtA []byte, err error) { } func (m *FetchTxnResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *FetchTxnResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) + var i int _ = i var l int _ = l - if len(m.MissingTxnList) > 0 { - for k := range m.MissingTxnList { - v := m.MissingTxnList[k] - baseI := i - if v != nil { - { - size, err := v.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - i = encodeVarintMessage(dAtA, i, uint64(k)) - i-- - dAtA[i] = 0x8 - i = encodeVarintMessage(dAtA, i, uint64(baseI-i)) - i-- - dAtA[i] = 0x1a - } + if m.ReplicaId != 0 { + dAtA[i] = 0x8 + i++ + i = encodeVarintMessage(dAtA, i, uint64(m.ReplicaId)) } if m.Height != 0 { - i = encodeVarintMessage(dAtA, i, uint64(m.Height)) - i-- dAtA[i] = 0x10 + i++ + i = encodeVarintMessage(dAtA, i, uint64(m.Height)) } - if m.ReplicaId != 0 { - i = encodeVarintMessage(dAtA, i, uint64(m.ReplicaId)) - i-- - dAtA[i] = 0x8 + if len(m.MissingTxnList) > 0 { + for k, _ := range m.MissingTxnList { + dAtA[i] = 0x1a + i++ + v := m.MissingTxnList[k] + msgSize := 0 + if v != nil { + msgSize = v.Size() + msgSize += 1 + sovMessage(uint64(msgSize)) + } + mapSize := 1 + sovMessage(uint64(k)) + msgSize + i = encodeVarintMessage(dAtA, i, uint64(mapSize)) + dAtA[i] = 0x8 + i++ + i = encodeVarintMessage(dAtA, i, uint64(k)) + if v != nil { + dAtA[i] = 0x12 + i++ + i = encodeVarintMessage(dAtA, i, uint64(v.Size())) + n1, err := v.MarshalTo(dAtA[i:]) + if err != nil { + return 0, err + } + i += n1 + } + } } - return len(dAtA) - i, nil + return i, nil } func encodeVarintMessage(dAtA []byte, offset int, v uint64) int { - offset -= sovMessage(v) - base := offset for v >= 1<<7 { dAtA[offset] = uint8(v&0x7f | 0x80) v >>= 7 offset++ } dAtA[offset] = uint8(v) - return base + return offset + 1 } func (m *TxSlice) Size() (n int) { if m == nil { @@ -447,7 +429,14 @@ func (m *FetchTxnResponse) Size() (n int) { } func sovMessage(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 + for { + n++ + x >>= 7 + if x == 0 { + break + } + } + return n } func sozMessage(x uint64) (n int) { return sovMessage(uint64((x << 1) ^ uint64((int64(x) >> 63)))) @@ -952,7 +941,6 @@ func (m *FetchTxnResponse) Unmarshal(dAtA []byte) error { func skipMessage(dAtA []byte) (n int, err error) { l := len(dAtA) iNdEx := 0 - depth := 0 for iNdEx < l { var wire uint64 for shift := uint(0); ; shift += 7 { @@ -984,8 +972,10 @@ func skipMessage(dAtA []byte) (n int, err error) { break } } + return iNdEx, nil case 1: iNdEx += 8 + return iNdEx, nil case 2: var length int for shift := uint(0); ; shift += 7 { @@ -1006,30 +996,55 @@ func skipMessage(dAtA []byte) (n int, err error) { return 0, ErrInvalidLengthMessage } iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupMessage + if iNdEx < 0 { + return 0, ErrInvalidLengthMessage } - depth-- + return iNdEx, nil + case 3: + for { + var innerWire uint64 + var start int = iNdEx + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowMessage + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + innerWire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + innerWireType := int(innerWire & 0x7) + if innerWireType == 4 { + break + } + next, err := skipMessage(dAtA[start:]) + if err != nil { + return 0, err + } + iNdEx = start + next + if iNdEx < 0 { + return 0, ErrInvalidLengthMessage + } + } + return iNdEx, nil + case 4: + return iNdEx, nil case 5: iNdEx += 4 + return iNdEx, nil default: return 0, fmt.Errorf("proto: illegal wireType %d", wireType) } - if iNdEx < 0 { - return 0, ErrInvalidLengthMessage - } - if depth == 0 { - return iNdEx, nil - } } - return 0, io.ErrUnexpectedEOF + panic("unreachable") } var ( - ErrInvalidLengthMessage = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowMessage = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupMessage = fmt.Errorf("proto: unexpected end of group") + ErrInvalidLengthMessage = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowMessage = fmt.Errorf("proto: integer overflow") ) diff --git a/pkg/order/mempool/storage.go b/pkg/order/mempool/storage.go index 87ae87e..5df996a 100644 --- a/pkg/order/mempool/storage.go +++ b/pkg/order/mempool/storage.go @@ -28,8 +28,8 @@ func (mpi *mempoolImpl) batchDelete(hashes []types.Hash) { batch.Commit() } -func (mpi *mempoolImpl) load(hash types.Hash) (*pb.Transaction, bool) { - txKey := compositeKey(hash.Bytes()) +func (mpi *mempoolImpl) load(hash []byte) (*pb.Transaction, bool) { + txKey := compositeKey(hash) txData := mpi.storage.Get(txKey) if txData == nil { return nil, false diff --git a/pkg/order/mempool/storage_test.go b/pkg/order/mempool/storage_test.go index 9b57c8a..a2a0797 100644 --- a/pkg/order/mempool/storage_test.go +++ b/pkg/order/mempool/storage_test.go @@ -15,19 +15,19 @@ func TestStorage(t *testing.T) { txList := make([]*pb.Transaction, 0) txHashList := make([]types.Hash, 0) - txHash1, _ := hex2Hash("txHash1") + txHash1 := newHash("txHash1") tx1 := &pb.Transaction{Nonce: uint64(1), TransactionHash: txHash1} - txHash2, _ := hex2Hash("txHash2") + txHash2 := newHash("txHash2") tx2 := &pb.Transaction{Nonce: uint64(1), TransactionHash: txHash2} txList = append(txList, tx1, tx2) - txHashList = append(txHashList, txHash1, txHash2) + txHashList = append(txHashList, *txHash1, *txHash1) mempool.batchStore(txList) - tx, ok := mempool.load(txHash1) + tx, ok := mempool.load(txHash1.Bytes()) ast.Equal(true, ok) ast.Equal(uint64(1), tx.Nonce) mempool.batchDelete(txHashList) - tx, ok = mempool.load(txHash1) + tx, ok = mempool.load(txHash1.Bytes()) ast.Equal(false, ok) ast.Nil(tx) } diff --git a/pkg/order/mempool/tx_store_test.go b/pkg/order/mempool/tx_store_test.go index 389baca..8b31b7c 100644 --- a/pkg/order/mempool/tx_store_test.go +++ b/pkg/order/mempool/tx_store_test.go @@ -24,14 +24,14 @@ func TestForward(t *testing.T) { txList = append(txList, tx1, tx2, tx3, tx4, tx5) err := mpi.processTransactions(txList) ast.Nil(err) - list := mpi.txStore.allTxs[account1.Hex()] + list := mpi.txStore.allTxs[account1.String()] ast.Equal(5, list.index.size()) ast.Equal(4, mpi.txStore.priorityIndex.size()) ast.Equal(1, mpi.txStore.parkingLotIndex.size()) removeList := list.forward(uint64(3)) ast.Equal(1, len(removeList)) - ast.Equal(2, len(removeList[account1.Hex()])) - ast.Equal(uint64(1), removeList[account1.Hex()][0].Nonce) - ast.Equal(uint64(2), removeList[account1.Hex()][1].Nonce) + ast.Equal(2, len(removeList[account1.String()])) + ast.Equal(uint64(1), removeList[account1.String()][0].Nonce) + ast.Equal(uint64(2), removeList[account1.String()][1].Nonce) } diff --git a/pkg/order/mempool/types.go b/pkg/order/mempool/types.go index 9169a6a..26def87 100644 --- a/pkg/order/mempool/types.go +++ b/pkg/order/mempool/types.go @@ -80,7 +80,7 @@ type Config struct { TxSliceTimeout time.Duration PeerMgr peermgr.PeerManager - GetTransactionFunc func(hash types.Hash) (*pb.Transaction, error) + GetTransactionFunc func(hash *types.Hash) (*pb.Transaction, error) ChainHeight uint64 Logger logrus.FieldLogger } diff --git a/pkg/order/mempool/util_test.go b/pkg/order/mempool/util_test.go index 5b089af..8c0c8ea 100644 --- a/pkg/order/mempool/util_test.go +++ b/pkg/order/mempool/util_test.go @@ -1,35 +1,11 @@ package mempool import ( - "fmt" "testing" - "github.com/meshplus/bitxhub-model/pb" - "github.com/stretchr/testify/assert" ) -func TestGetAccount(t *testing.T) { - ast := assert.New(t) - privKey := genPrivKey() - address, _ := privKey.PublicKey().Address() - tx := constructIBTPTx(uint64(1), &privKey) - addr, err := getAccount(tx) - ast.Nil(err) - expectedAddr := fmt.Sprintf("%s-%s-%d", address, address, pb.IBTP_INTERCHAIN) - ast.Equal(expectedAddr, addr) - - data := &pb.TransactionData{ - Payload: []byte("test"), - } - tx = &pb.Transaction{ - To: InterchainContractAddr, - Data: data, - } - _, err = getAccount(tx) - ast.NotNil(err.Error(), "unmarshal invoke payload faile") -} - func TestPoolIsFull(t *testing.T) { ast := assert.New(t) mpi, _ := mockMempoolImpl() diff --git a/pkg/order/mempool/utils.go b/pkg/order/mempool/utils.go index f232ad7..4422e28 100644 --- a/pkg/order/mempool/utils.go +++ b/pkg/order/mempool/utils.go @@ -1,16 +1,11 @@ package mempool import ( - "encoding/hex" - "errors" - "fmt" "strconv" "sync/atomic" "time" - "github.com/meshplus/bitxhub-kit/types" "github.com/meshplus/bitxhub-model/pb" - "github.com/meshplus/bitxhub/internal/constant" raftproto "github.com/meshplus/bitxhub/pkg/order/etcdraft/proto" cmap "github.com/orcaman/concurrent-map" @@ -62,23 +57,6 @@ func newNonceCache() *nonceCache { } } -// TODO (YH): refactor the tx struct -func hex2Hash(hash string) (types.Hash, error) { - var ( - hubHash types.Hash - hashBytes []byte - err error - ) - if hashBytes, err = hex.DecodeString(hash); err != nil { - return types.Hash{}, err - } - if len(hashBytes) != types.HashLength { - return types.Hash{}, errors.New("invalid tx hash") - } - copy(hubHash[:], hashBytes) - return hubHash, nil -} - func (mpi *mempoolImpl) poolIsFull() bool { return atomic.LoadInt32(&mpi.txStore.poolSize) >= DefaultPoolSize } @@ -124,22 +102,3 @@ func newTimer(d time.Duration) *timerManager { timeoutEventC: make(chan bool), } } - -func getAccount(tx *pb.Transaction) (string, error) { - if tx.To != constant.InterchainContractAddr.Address() { - return tx.From.Hex(), nil - } - payload := &pb.InvokePayload{} - if err := payload.Unmarshal(tx.Data.Payload); err != nil { - return "", fmt.Errorf("unmarshal invoke payload failed: %s", err.Error()) - } - if payload.Method == IBTPMethod1 || payload.Method == IBTPMethod2 { - ibtp := &pb.IBTP{} - if err := ibtp.Unmarshal(payload.Args[0].Value); err != nil { - return "", fmt.Errorf("unmarshal ibtp from tx :%w", err) - } - account := fmt.Sprintf("%s-%s-%d", ibtp.From, ibtp.To, ibtp.Category()) - return account, nil - } - return tx.From.Hex(), nil -} diff --git a/pkg/order/solo/node.go b/pkg/order/solo/node.go index 246e478..d4fc92d 100644 --- a/pkg/order/solo/node.go +++ b/pkg/order/solo/node.go @@ -21,7 +21,7 @@ type Node struct { commitC chan *pb.Block // block channel logger logrus.FieldLogger // logger reqLookUp *order.ReqLookUp // bloom filter - getTransactionFunc func(hash types.Hash) (*pb.Transaction, error) + getTransactionFunc func(hash *types.Hash) (*pb.Transaction, error) packSize int // maximum number of transaction packages blockTick time.Duration // block packed period @@ -87,7 +87,7 @@ func (n *Node) ReportState(height uint64, hash types.Hash) { if height%10 == 0 { n.logger.WithFields(logrus.Fields{ "height": height, - "hash": hash.ShortString(), + "hash": hash.String(), }).Info("Report checkpoint") } } diff --git a/pkg/order/solo/node_test.go b/pkg/order/solo/node_test.go index e76e6ec..f15527a 100644 --- a/pkg/order/solo/node_test.go +++ b/pkg/order/solo/node_test.go @@ -43,13 +43,11 @@ func TestNode_Start(t *testing.T) { tx := &pb.Transaction{ From: from, - To: types.String2Address(to), - Data: &pb.TransactionData{ - Amount: 10, - }, + To: types.NewAddressByStr(to), Timestamp: time.Now().UnixNano(), Nonce: uint64(rand.Int63()), } + tx.TransactionHash = tx.Hash() err = tx.Sign(privKey) require.Nil(t, err) diff --git a/pkg/proof/proof_pool.go b/pkg/proof/proof_pool.go index 19ce338..ab33ad4 100644 --- a/pkg/proof/proof_pool.go +++ b/pkg/proof/proof_pool.go @@ -5,7 +5,6 @@ import ( "crypto/sha256" "encoding/json" "fmt" - "strings" "sync" appchainMgr "github.com/meshplus/bitxhub-core/appchain-mgr" @@ -41,7 +40,8 @@ func (pl *VerifyPool) ValidationEngine() *validator.ValidationEngine { } func (pl *VerifyPool) CheckProof(tx *pb.Transaction) (bool, error) { - if ibtp := pl.extractIBTP(tx); ibtp != nil { + ibtp := tx.IBTP + if ibtp != nil { ok, err := pl.verifyProof(ibtp, tx.Extra) if err != nil { pl.logger.WithFields(logrus.Fields{ @@ -63,32 +63,6 @@ func (pl *VerifyPool) CheckProof(tx *pb.Transaction) (bool, error) { return true, nil } -func (pl *VerifyPool) extractIBTP(tx *pb.Transaction) *pb.IBTP { - if strings.ToLower(tx.To.String()) != constant.InterchainContractAddr.String() { - return nil - } - if tx.Data.VmType != pb.TransactionData_BVM { - return nil - } - ip := &pb.InvokePayload{} - if err := ip.Unmarshal(tx.Data.Payload); err != nil { - return nil - } - if ip.Method != "HandleIBTP" { - return nil - } - if len(ip.Args) != 1 { - return nil - } - - ibtp := &pb.IBTP{} - if err := ibtp.Unmarshal(ip.Args[0].Value); err != nil { - pl.logger.Error(err) - return nil - } - return ibtp -} - func (pl *VerifyPool) verifyProof(ibtp *pb.IBTP, proof []byte) (bool, error) { if proof == nil { return false, fmt.Errorf("empty proof") diff --git a/pkg/vm/boltvm/bolt_stub.go b/pkg/vm/boltvm/bolt_stub.go index 11ab4f8..d65045e 100755 --- a/pkg/vm/boltvm/bolt_stub.go +++ b/pkg/vm/boltvm/bolt_stub.go @@ -19,11 +19,11 @@ type BoltStubImpl struct { } func (b *BoltStubImpl) Caller() string { - return b.ctx.Caller.Hex() + return b.ctx.Caller.String() } func (b *BoltStubImpl) Callee() string { - return b.ctx.Callee.Hex() + return b.ctx.Callee.String() } func (b *BoltStubImpl) Logger() logrus.FieldLogger { @@ -31,7 +31,7 @@ func (b *BoltStubImpl) Logger() logrus.FieldLogger { } // GetTxHash returns the transaction hash -func (b *BoltStubImpl) GetTxHash() types.Hash { +func (b *BoltStubImpl) GetTxHash() *types.Hash { hash := b.ctx.TransactionHash return hash } @@ -115,7 +115,7 @@ func (b *BoltStubImpl) postEvent(interchain bool, event interface{}) { } func (b *BoltStubImpl) CrossInvoke(address, method string, args ...*pb.Arg) *Response { - addr := types.String2Address(address) + addr := types.NewAddressByStr(address) payload := &pb.InvokePayload{ Method: method, diff --git a/pkg/vm/boltvm/boltvm.go b/pkg/vm/boltvm/boltvm.go index 6cd5db3..12bb91a 100755 --- a/pkg/vm/boltvm/boltvm.go +++ b/pkg/vm/boltvm/boltvm.go @@ -40,7 +40,7 @@ func (bvm *BoltVM) Run(input []byte) (ret []byte, err error) { return nil, fmt.Errorf("unmarshal invoke payload: %w", err) } - contract, err := GetBoltContract(bvm.ctx.Callee.Hex(), bvm.contracts) + contract, err := GetBoltContract(bvm.ctx.Callee.String(), bvm.contracts) if err != nil { return nil, fmt.Errorf("get bolt contract: %w", err) } diff --git a/pkg/vm/boltvm/context.go b/pkg/vm/boltvm/context.go index c9878d1..567b519 100644 --- a/pkg/vm/boltvm/context.go +++ b/pkg/vm/boltvm/context.go @@ -8,11 +8,11 @@ import ( ) type Context struct { - caller types.Address - callee types.Address + caller *types.Address + callee *types.Address ledger ledger.Ledger transactionIndex uint64 - transactionHash types.Hash + transactionHash *types.Hash logger logrus.FieldLogger } @@ -28,18 +28,18 @@ func NewContext(tx *pb.Transaction, txIndex uint64, data *pb.TransactionData, le } func (ctx *Context) Caller() string { - return ctx.caller.Hex() + return ctx.caller.String() } func (ctx *Context) Callee() string { - return ctx.callee.Hex() + return ctx.callee.String() } func (ctx *Context) TransactionIndex() uint64 { return ctx.transactionIndex } -func (ctx *Context) TransactionHash() types.Hash { +func (ctx *Context) TransactionHash() *types.Hash { return ctx.transactionHash } diff --git a/pkg/vm/boltvm/stub.go b/pkg/vm/boltvm/stub.go index 90292e4..1690146 100644 --- a/pkg/vm/boltvm/stub.go +++ b/pkg/vm/boltvm/stub.go @@ -16,7 +16,7 @@ type Stub interface { // Logger Logger() logrus.FieldLogger // GetTxHash returns the transaction hash - GetTxHash() types.Hash + GetTxHash() *types.Hash // GetTxIndex returns the transaction index in the block GetTxIndex() uint64 // Has judges key diff --git a/pkg/vm/context.go b/pkg/vm/context.go index 1248950..2dd2e52 100644 --- a/pkg/vm/context.go +++ b/pkg/vm/context.go @@ -9,11 +9,11 @@ import ( // Context represents the context of wasm type Context struct { - Caller types.Address - Callee types.Address + Caller *types.Address + Callee *types.Address Ledger ledger.Ledger TransactionIndex uint64 - TransactionHash types.Hash + TransactionHash *types.Hash TransactionData *pb.TransactionData Nonce uint64 Logger logrus.FieldLogger diff --git a/pkg/vm/wasm/context.go b/pkg/vm/wasm/context.go index ea74733..edcf18d 100755 --- a/pkg/vm/wasm/context.go +++ b/pkg/vm/wasm/context.go @@ -9,8 +9,8 @@ import ( // Context represents the context of wasm type Context struct { - caller types.Address - callee types.Address + caller *types.Address + callee *types.Address ledger ledger.Ledger transactionData *pb.TransactionData nonce int64 @@ -31,12 +31,12 @@ func NewContext(tx *pb.Transaction, data *pb.TransactionData, ledger ledger.Ledg // Caller returns the tx caller address func (ctx *Context) Caller() string { - return ctx.caller.Hex() + return ctx.caller.String() } // Callee returns the tx callee address func (ctx *Context) Callee() string { - return ctx.callee.Hex() + return ctx.callee.String() } // Logger returns the log instance diff --git a/pkg/vm/wasm/wasm.go b/pkg/vm/wasm/wasm.go index f973efc..a53322c 100755 --- a/pkg/vm/wasm/wasm.go +++ b/pkg/vm/wasm/wasm.go @@ -1,14 +1,15 @@ package wasm import ( + "bytes" "crypto/sha256" + "encoding/binary" "encoding/json" "fmt" "sync" - "github.com/ethereum/go-ethereum/rlp" + "github.com/meshplus/bitxhub-core/wasm" "github.com/meshplus/bitxhub-kit/types" - "github.com/meshplus/bitxhub-kit/wasm" "github.com/meshplus/bitxhub/pkg/vm" "github.com/wasmerio/go-ext-wasm/wasmer" ) @@ -43,7 +44,7 @@ func New(ctx *vm.Context, imports *wasmer.Imports, instances map[string]wasmer.I ctx: ctx, } - if ctx.Callee == (types.Address{}) { + if ctx.Callee == nil || bytes.Equal(ctx.Callee.Bytes(), (&types.Address{}).Bytes()) { return wasmVM, nil } @@ -70,7 +71,7 @@ func EmptyImports() (*wasmer.Imports, error) { // Run let the wasm vm excute or deploy the smart contract which depends on whether the callee is empty func (w *WasmVM) Run(input []byte) (ret []byte, err error) { - if w.ctx.Callee == (types.Address{}) { + if w.ctx.Callee == nil || bytes.Equal(w.ctx.Callee.Bytes(), (&types.Address{}).Bytes()) { return w.deploy() } @@ -86,7 +87,7 @@ func (w *WasmVM) deploy() ([]byte, error) { contractAddr := createAddress(w.ctx.Caller, contractNonce) wasmStruct := &Contract{ Code: w.ctx.TransactionData.Payload, - Hash: types.Bytes2Hash(w.ctx.TransactionData.Payload), + Hash: *types.NewHash(w.ctx.TransactionData.Payload), } wasmByte, err := json.Marshal(wasmStruct) if err != nil { @@ -99,9 +100,14 @@ func (w *WasmVM) deploy() ([]byte, error) { return contractAddr.Bytes(), nil } -func createAddress(b types.Address, nonce uint64) types.Address { - data, _ := rlp.EncodeToBytes([]interface{}{b, nonce}) +func createAddress(b *types.Address, nonce uint64) *types.Address { + var data []byte + nonceBytes := make([]byte, 8) + + binary.LittleEndian.PutUint64(nonceBytes, nonce) + data = append(data, b.Bytes()...) + data = append(data, nonceBytes...) hashBytes := sha256.Sum256(data) - return types.Bytes2Address(hashBytes[12:]) + return types.NewAddress(hashBytes[12:]) } diff --git a/pkg/vm/wasm/wasm_test.go b/pkg/vm/wasm/wasm_test.go index 211de24..1e2e928 100755 --- a/pkg/vm/wasm/wasm_test.go +++ b/pkg/vm/wasm/wasm_test.go @@ -67,6 +67,7 @@ func initCreateContext(t *testing.T, name string) *vm.Context { return &vm.Context{ Caller: caller, + Callee: &types.Address{}, TransactionData: data, Ledger: ldg, } @@ -173,7 +174,7 @@ func TestExecute(t *testing.T) { } ctx1 := &vm.Context{ Caller: ctx.Caller, - Callee: types.Bytes2Address(ret), + Callee: types.NewAddress(ret), TransactionData: data, Ledger: ctx.Ledger, } @@ -221,7 +222,7 @@ func TestWasm_RunFabValidation(t *testing.T) { } ctx1 := &vm.Context{ Caller: ctx.Caller, - Callee: types.Bytes2Address(ret), + Callee: types.NewAddress(ret), TransactionData: data, Ledger: ctx.Ledger, } @@ -288,7 +289,7 @@ func BenchmarkRunFabValidation(b *testing.B) { require.Nil(b, err) ctx1 := &vm.Context{ Caller: ctx.Caller, - Callee: types.Bytes2Address(ret), + Callee: types.NewAddress(ret), TransactionData: data, Ledger: ctx.Ledger, } @@ -334,7 +335,7 @@ func TestWasm_RunWithoutMethod(t *testing.T) { } ctx1 := &vm.Context{ Caller: ctx.Caller, - Callee: types.Bytes2Address(ret), + Callee: types.NewAddress(ret), TransactionData: data, Ledger: ctx.Ledger, } @@ -361,7 +362,7 @@ BcNwjTDCxyxLNjFKQfMAc6sY6iJs+Ma59WZyC/4uhjE= return &repo.Repo{ Key: &repo.Key{ PrivKey: privKey, - Address: address.Hex(), + Address: address.String(), }, } } diff --git a/tester/case001_api_test.go b/tester/case001_api_test.go index 8944350..96d4126 100644 --- a/tester/case001_api_test.go +++ b/tester/case001_api_test.go @@ -23,7 +23,7 @@ type API struct { suite.Suite api api.CoreAPI privKey crypto.PrivateKey - from types.Address + from *types.Address } func (suite *API) SetupSuite() { @@ -54,7 +54,7 @@ func (suite *API) TestSend() { testSendView(suite) } -func testSendTransaction(suite *API) types.Hash { +func testSendTransaction(suite *API) *types.Hash { tx, err := genContractTransaction(pb.TransactionData_BVM, suite.privKey, 1, constant.StoreContractAddr.Address(), "Set", pb.String("key"), pb.String(value)) suite.Nil(err) diff --git a/tester/case002_appchain_test.go b/tester/case002_appchain_test.go index 9eea782..04df7bf 100755 --- a/tester/case002_appchain_test.go +++ b/tester/case002_appchain_test.go @@ -20,7 +20,7 @@ type RegisterAppchain struct { suite.Suite api api.CoreAPI privKey crypto.PrivateKey - from types.Address + from *types.Address } type Appchain struct { diff --git a/tester/case003_interchain_test.go b/tester/case003_interchain_test.go index 5b09776..e944015 100644 --- a/tester/case003_interchain_test.go +++ b/tester/case003_interchain_test.go @@ -75,18 +75,15 @@ func (suite *Interchain) TestHandleIBTP() { k1Nonce++ // register rule - ret, err = invokeBVMContract(suite.api, k1, k1Nonce, constant.RuleManagerContractAddr.Address(), "RegisterRule", pb.String(f.Hex()), pb.String(addr.Hex())) + ret, err = invokeBVMContract(suite.api, k1, k1Nonce, constant.RuleManagerContractAddr.Address(), "RegisterRule", pb.String(f.String()), pb.String(addr.String())) suite.Require().Nil(err) suite.Require().True(ret.IsSuccess()) k1Nonce++ proof := []byte("true") proofHash := sha256.Sum256(proof) - ib := &pb.IBTP{From: f.Hex(), To: t.Hex(), Index: 1, Timestamp: time.Now().UnixNano(), Proof: proofHash[:]} - data, err := ib.Marshal() - suite.Require().Nil(err) - - tx, err := genBVMContractTransaction(k1, ibtpNonce, constant.InterchainContractAddr.Address(), "HandleIBTP", pb.Bytes(data)) + ib := &pb.IBTP{From: f.String(), To: t.String(), Index: ibtpNonce, Timestamp: time.Now().UnixNano(), Proof: proofHash[:]} + tx, err := genIBTPTransaction(k1, ib) suite.Require().Nil(err) tx.Extra = proof @@ -150,7 +147,7 @@ func (suite *Interchain) TestGetIBTPByID() { k1Nonce++ // register rule - _, err = invokeBVMContract(suite.api, k1, k1Nonce, constant.RuleManagerContractAddr.Address(), "RegisterRule", pb.String(f.Hex()), pb.String(addr.Hex())) + _, err = invokeBVMContract(suite.api, k1, k1Nonce, constant.RuleManagerContractAddr.Address(), "RegisterRule", pb.String(f.String()), pb.String(addr.String())) suite.Require().Nil(err) k1Nonce++ @@ -158,11 +155,8 @@ func (suite *Interchain) TestGetIBTPByID() { suite.Require().Nil(err) proofHash := sha256.Sum256(proof) - ib := &pb.IBTP{From: f.Hex(), To: t.Hex(), Index: 1, Payload: []byte("111"), Timestamp: time.Now().UnixNano(), Proof: proofHash[:]} - data, err := ib.Marshal() - suite.Require().Nil(err) - - tx, err := genBVMContractTransaction(k1, ibtpNonce, constant.InterchainContractAddr.Address(), "HandleIBTP", pb.Bytes(data)) + ib := &pb.IBTP{From: f.String(), To: t.String(), Index: ibtpNonce, Payload: []byte("111"), Timestamp: time.Now().UnixNano(), Proof: proofHash[:]} + tx, err := genIBTPTransaction(k1, ib) suite.Require().Nil(err) tx.Extra = proof receipt, err := sendTransactionWithReceipt(suite.api, tx) @@ -170,11 +164,8 @@ func (suite *Interchain) TestGetIBTPByID() { suite.Require().EqualValues(true, receipt.IsSuccess(), string(receipt.Ret)) ibtpNonce++ - ib.Index = 2 - data, err = ib.Marshal() - suite.Require().Nil(err) - - tx, err = genBVMContractTransaction(k1, ibtpNonce, constant.InterchainContractAddr.Address(), "HandleIBTP", pb.Bytes(data)) + ib2 := &pb.IBTP{From: f.String(), To: t.String(), Index: ibtpNonce, Payload: []byte("111"), Timestamp: time.Now().UnixNano(), Proof: proofHash[:]} + tx, err = genIBTPTransaction(k1, ib2) suite.Require().Nil(err) tx.Extra = proof receipt, err = sendTransactionWithReceipt(suite.api, tx) @@ -182,11 +173,8 @@ func (suite *Interchain) TestGetIBTPByID() { suite.Require().EqualValues(true, receipt.IsSuccess(), string(receipt.Ret)) ibtpNonce++ - ib.Index = 3 - data, err = ib.Marshal() - suite.Assert().Nil(err) - - tx, err = genBVMContractTransaction(k1, ibtpNonce, constant.InterchainContractAddr.Address(), "HandleIBTP", pb.Bytes(data)) + ib3 := &pb.IBTP{From: f.String(), To: t.String(), Index: ibtpNonce, Payload: []byte("111"), Timestamp: time.Now().UnixNano(), Proof: proofHash[:]} + tx, err = genIBTPTransaction(k1, ib3) suite.Require().Nil(err) tx.Extra = proof receipt, err = sendTransactionWithReceipt(suite.api, tx) diff --git a/tester/case004_role_test.go b/tester/case004_role_test.go index 84b2feb..edcbf6d 100644 --- a/tester/case004_role_test.go +++ b/tester/case004_role_test.go @@ -6,13 +6,14 @@ import ( "path/filepath" "strconv" + "github.com/tidwall/gjson" + "github.com/meshplus/bitxhub-kit/crypto" "github.com/meshplus/bitxhub-kit/crypto/asym" "github.com/meshplus/bitxhub-model/pb" "github.com/meshplus/bitxhub/internal/constant" "github.com/meshplus/bitxhub/internal/coreapi/api" "github.com/stretchr/testify/suite" - "github.com/tidwall/gjson" ) type Role struct { @@ -80,7 +81,7 @@ func (suite *Role) TestIsAdmin() { suite.Require().Nil(err) kNonce := uint64(1) - r, err := invokeBVMContract(suite.api, k, kNonce, constant.RoleContractAddr.Address(), "IsAdmin", pb.String(from.Hex())) + r, err := invokeBVMContract(suite.api, k, kNonce, constant.RoleContractAddr.Address(), "IsAdmin", pb.String(from.String())) suite.Assert().Nil(err) ret, err := strconv.ParseBool(string(r.Ret)) suite.Assert().Nil(err) @@ -94,9 +95,9 @@ func (suite *Role) TestIsAdmin() { suite.Require().Nil(err) fromAdmin, err := priAdmin.PublicKey().Address() suite.Require().Nil(err) - adminNonce := suite.api.Broker().GetPendingNonceByAccount(fromAdmin.Hex()) + adminNonce := suite.api.Broker().GetPendingNonceByAccount(fromAdmin.String()) - r, err = invokeBVMContract(suite.api, priAdmin, adminNonce, constant.RoleContractAddr.Address(), "IsAdmin", pb.String(fromAdmin.Hex())) + r, err = invokeBVMContract(suite.api, priAdmin, adminNonce, constant.RoleContractAddr.Address(), "IsAdmin", pb.String(fromAdmin.String())) suite.Require().Nil(err) suite.Require().True(r.IsSuccess()) ret, err = strconv.ParseBool(string(r.Ret)) @@ -176,12 +177,12 @@ func (suite *Role) TestGetRuleAddress() { suite.Require().NotEqual(addr1, addr2) // register rule - ret, err = invokeBVMContract(suite.api, k1, k1Nonce, constant.RuleManagerContractAddr.Address(), "RegisterRule", pb.String(f1.Hex()), pb.String(addr1.Hex())) + ret, err = invokeBVMContract(suite.api, k1, k1Nonce, constant.RuleManagerContractAddr.Address(), "RegisterRule", pb.String(f1.String()), pb.String(addr1.String())) suite.Require().Nil(err) suite.Require().True(ret.IsSuccess()) k1Nonce++ - ret, err = invokeBVMContract(suite.api, k2, k2Nonce, constant.RuleManagerContractAddr.Address(), "RegisterRule", pb.String(f2.Hex()), pb.String(addr2.Hex())) + ret, err = invokeBVMContract(suite.api, k2, k2Nonce, constant.RuleManagerContractAddr.Address(), "RegisterRule", pb.String(f2.String()), pb.String(addr2.String())) suite.Require().Nil(err) suite.Require().True(ret.IsSuccess()) k2Nonce++ @@ -210,7 +211,7 @@ func (suite *Role) TestSetAdminRoles() { suite.Require().Nil(err) pubAdmin, err := priAdmin.PublicKey().Bytes() suite.Require().Nil(err) - adminNonce := suite.api.Broker().GetPendingNonceByAccount(fromAdmin.Hex()) + adminNonce := suite.api.Broker().GetPendingNonceByAccount(fromAdmin.String()) // register retReg, err := invokeBVMContract(suite.api, priAdmin, adminNonce, constant.AppchainMgrContractAddr.Address(), "Register", @@ -227,7 +228,7 @@ func (suite *Role) TestSetAdminRoles() { adminNonce++ // is admin - retIsAdmin, err := invokeBVMContract(suite.api, priAdmin, adminNonce, constant.RoleContractAddr.Address(), "IsAdmin", pb.String(fromAdmin.Hex())) + retIsAdmin, err := invokeBVMContract(suite.api, priAdmin, adminNonce, constant.RoleContractAddr.Address(), "IsAdmin", pb.String(fromAdmin.String())) suite.Require().Nil(err) suite.Require().True(retIsAdmin.IsSuccess()) adminNonce++ @@ -240,7 +241,7 @@ func (suite *Role) TestSetAdminRoles() { adminNonce++ as := make([]string, 0) - as = append(as, fromAdmin.Hex()) + as = append(as, fromAdmin.String()) data, err := json.Marshal(as) suite.Nil(err) @@ -282,7 +283,7 @@ func (suite *Role) TestSetAdminRoles() { // set admin roles as2 := make([]string, 0) - as2 = append(as2, fromAdmin.Hex(), fromAdmin2.Hex(), fromAdmin3.Hex(), fromAdmin4.Hex()) + as2 = append(as2, fromAdmin.String(), fromAdmin2.String(), fromAdmin3.String(), fromAdmin4.String()) data2, err := json.Marshal(as2) suite.Nil(err) r, err = invokeBVMContract(suite.api, priAdmin, adminNonce, constant.RoleContractAddr.Address(), "SetAdminRoles", pb.String(string(data2))) diff --git a/tester/helper.go b/tester/helper.go index a4e6872..a4fa737 100644 --- a/tester/helper.go +++ b/tester/helper.go @@ -6,22 +6,72 @@ import ( "strings" "time" - "github.com/meshplus/bitxhub/internal/coreapi/api" - "github.com/meshplus/bitxhub-kit/crypto" "github.com/meshplus/bitxhub-kit/types" "github.com/meshplus/bitxhub-model/pb" + "github.com/meshplus/bitxhub/internal/constant" + "github.com/meshplus/bitxhub/internal/coreapi/api" ) -func genBVMContractTransaction(privateKey crypto.PrivateKey, nonce uint64, address types.Address, method string, args ...*pb.Arg) (*pb.Transaction, error) { +func genBVMContractTransaction(privateKey crypto.PrivateKey, nonce uint64, address *types.Address, method string, args ...*pb.Arg) (*pb.Transaction, error) { return genContractTransaction(pb.TransactionData_BVM, privateKey, nonce, address, method, args...) } -func genXVMContractTransaction(privateKey crypto.PrivateKey, nonce uint64, address types.Address, method string, args ...*pb.Arg) (*pb.Transaction, error) { +func genXVMContractTransaction(privateKey crypto.PrivateKey, nonce uint64, address *types.Address, method string, args ...*pb.Arg) (*pb.Transaction, error) { return genContractTransaction(pb.TransactionData_XVM, privateKey, nonce, address, method, args...) } -func invokeBVMContract(api api.CoreAPI, privateKey crypto.PrivateKey, nonce uint64, address types.Address, method string, args ...*pb.Arg) (*pb.Receipt, error) { +func genIBTPTransaction(privateKey crypto.PrivateKey, ibtp *pb.IBTP) (*pb.Transaction, error) { + from, err := privateKey.PublicKey().Address() + if err != nil { + return nil, err + } + + ibtpd, err := ibtp.Marshal() + if err != nil { + return nil, err + } + + pl := &pb.InvokePayload{ + Method: "HandleIBTP", + Args: []*pb.Arg{pb.Bytes(ibtpd)}, + } + + data, err := pl.Marshal() + if err != nil { + return nil, err + } + + td := &pb.TransactionData{ + Type: pb.TransactionData_INVOKE, + VmType: pb.TransactionData_BVM, + Payload: data, + } + + payload, err := td.Marshal() + if err != nil { + return nil, err + } + + tx := &pb.Transaction{ + From: from, + To: constant.InterchainContractAddr.Address(), + Payload: payload, + Timestamp: time.Now().UnixNano(), + Nonce: ibtp.Index, + IBTP: ibtp, + } + + if err := tx.Sign(privateKey); err != nil { + return nil, fmt.Errorf("tx sign: %w", err) + } + + tx.TransactionHash = tx.Hash() + + return tx, nil +} + +func invokeBVMContract(api api.CoreAPI, privateKey crypto.PrivateKey, nonce uint64, address *types.Address, method string, args ...*pb.Arg) (*pb.Receipt, error) { tx, err := genBVMContractTransaction(privateKey, nonce, address, method, args...) if err != nil { return nil, err @@ -60,7 +110,7 @@ func sendTransactionWithReceipt(api api.CoreAPI, tx *pb.Transaction) (*pb.Receip } -func genContractTransaction(vmType pb.TransactionData_VMType, privateKey crypto.PrivateKey, nonce uint64, address types.Address, method string, args ...*pb.Arg) (*pb.Transaction, error) { +func genContractTransaction(vmType pb.TransactionData_VMType, privateKey crypto.PrivateKey, nonce uint64, address *types.Address, method string, args ...*pb.Arg) (*pb.Transaction, error) { from, err := privateKey.PublicKey().Address() if err != nil { return nil, err @@ -82,10 +132,15 @@ func genContractTransaction(vmType pb.TransactionData_VMType, privateKey crypto. Payload: data, } + payload, err := td.Marshal() + if err != nil { + return nil, err + } + tx := &pb.Transaction{ From: from, To: address, - Data: td, + Payload: payload, Timestamp: time.Now().UnixNano(), Nonce: nonce, } @@ -99,10 +154,10 @@ func genContractTransaction(vmType pb.TransactionData_VMType, privateKey crypto. return tx, nil } -func deployContract(api api.CoreAPI, privateKey crypto.PrivateKey, nonce uint64, contract []byte) (types.Address, error) { +func deployContract(api api.CoreAPI, privateKey crypto.PrivateKey, nonce uint64, contract []byte) (*types.Address, error) { from, err := privateKey.PublicKey().Address() if err != nil { - return types.Address{}, err + return nil, err } td := &pb.TransactionData{ @@ -111,9 +166,14 @@ func deployContract(api api.CoreAPI, privateKey crypto.PrivateKey, nonce uint64, Payload: contract, } + payload, err := td.Marshal() + if err != nil { + return nil, err + } + tx := &pb.Transaction{ From: from, - Data: td, + Payload: payload, Timestamp: time.Now().UnixNano(), Nonce: nonce, } @@ -121,15 +181,15 @@ func deployContract(api api.CoreAPI, privateKey crypto.PrivateKey, nonce uint64, tx.TransactionHash = tx.Hash() if err := tx.Sign(privateKey); err != nil { - return types.Address{}, fmt.Errorf("tx sign: %w", err) + return nil, fmt.Errorf("tx sign: %w", err) } receipt, err := sendTransactionWithReceipt(api, tx) if err != nil { - return types.Address{}, err + return nil, err } - ret := types.Bytes2Address(receipt.GetRet()) + ret := types.NewAddress(receipt.GetRet()) return ret, nil } diff --git a/tester/tester_test.go b/tester/tester_test.go index bbb8be5..1b0c5ed 100644 --- a/tester/tester_test.go +++ b/tester/tester_test.go @@ -4,13 +4,14 @@ import ( "testing" "time" + "github.com/stretchr/testify/suite" + "github.com/meshplus/bitxhub/internal/app" "github.com/meshplus/bitxhub/internal/coreapi" "github.com/meshplus/bitxhub/internal/coreapi/api" "github.com/meshplus/bitxhub/internal/loggers" "github.com/meshplus/bitxhub/internal/repo" "github.com/stretchr/testify/require" - "github.com/stretchr/testify/suite" ) func TestTester(t *testing.T) {