From 361f00167f4b503b2d5985392a31b2237f3e5e50 Mon Sep 17 00:00:00 2001 From: dinhln89 Date: Wed, 20 Jun 2018 14:35:00 +0700 Subject: [PATCH 1/2] Fixed send tx sign to smart contract for block signer. --- eth/backend.go | 29 ++++++++++------------------- eth/fetcher/fetcher.go | 33 ++++++++++----------------------- 2 files changed, 20 insertions(+), 42 deletions(-) diff --git a/eth/backend.go b/eth/backend.go index 2668d6c37e..dde6889a0f 100644 --- a/eth/backend.go +++ b/eth/backend.go @@ -219,7 +219,6 @@ func New(ctx *node.ServiceContext, config *Config) (*Ethereum, error) { startBlockNumber := number - (rCheckpoint * 2) + 1 endBlockNumber := startBlockNumber + rCheckpoint - 1 signers := make(map[common.Address]*rewardLog) - validators := make(map[common.Address]*rewardLog) totalSigner := uint64(0) for i := startBlockNumber; i <= endBlockNumber; i++ { @@ -239,14 +238,18 @@ func New(ctx *node.ServiceContext, config *Config) (*Ethereum, error) { } // Get validator in blockSigner smartcontract. - addrs, _ := blockSigner.GetSigners(opts, new(big.Int).SetUint64(i)) + addrs, err := blockSigner.GetSigners(opts, new(big.Int).SetUint64(i)) + if err != nil { + log.Error("TOMO - Fail to get signers from smartcontract.", "error", err) + return err + } if len(addrs) > 0 { for j := 0; j < len(addrs); j++ { - _, exist := validators[addrs[j]] + _, exist := signers[addrs[j]] if exist { - validators[addrs[j]].Sign++ + signers[addrs[j]].Sign++ } else { - validators[addrs[j]] = &rewardLog{1, 0} + signers[addrs[j]] = &rewardLog{1, 0} } totalSigner++ } @@ -256,6 +259,7 @@ func New(ctx *node.ServiceContext, config *Config) (*Ethereum, error) { chainReward := new(big.Int).SetUint64(chain.Config().Clique.Reward * params.Ether) // Add reward for signer. calcReward := new(big.Int) + // Add reward for validators. for signer, rLog := range signers { calcReward.Mul(chainReward, new(big.Int).SetUint64(rLog.Sign)) calcReward.Div(calcReward, new(big.Int).SetUint64(totalSigner)) @@ -263,26 +267,13 @@ func New(ctx *node.ServiceContext, config *Config) (*Ethereum, error) { state.AddBalance(signer, calcReward) } - // Add reward for validators. - for validator, rLog := range validators { - calcReward.Mul(chainReward, new(big.Int).SetUint64(rLog.Sign)) - calcReward.Div(calcReward, new(big.Int).SetUint64(totalSigner)) - rLog.Reward = float64(calcReward.Int64()) - - state.AddBalance(validator, calcReward) - } jsonSigners, err := json.Marshal(signers) if err != nil { log.Error("TOMO - Fail to parse json signers", "error", err) return err } - jsonValidators, err := json.Marshal(validators) - if err != nil { - log.Error("TOMO - Fail to parse json validators", "error", err) - return err - } - log.Info("TOMO - Calculate reward at checkpoint", "startBlock", startBlockNumber, "endBlock", endBlockNumber, "signers", string(jsonSigners), "totalSigner", totalSigner, "totalReward", chainReward, "validators", string(jsonValidators)) + log.Info("TOMO - Calculate reward at checkpoint", "startBlock", startBlockNumber, "endBlock", endBlockNumber, "signers", string(jsonSigners), "totalSigner", totalSigner, "totalReward", chainReward) } return nil diff --git a/eth/fetcher/fetcher.go b/eth/fetcher/fetcher.go index 13a486b149..11b9a360b8 100644 --- a/eth/fetcher/fetcher.go +++ b/eth/fetcher/fetcher.go @@ -25,7 +25,6 @@ import ( "github.com/ethereum/go-ethereum/accounts" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/consensus" - "github.com/ethereum/go-ethereum/consensus/clique" "github.com/ethereum/go-ethereum/core" "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/log" @@ -743,8 +742,6 @@ func (f *Fetcher) forgetBlock(hash common.Hash) { // Create tx for sign to smartcontract after import block into chain. func (f *Fetcher) CreateTransactionSign(chainConfig *params.ChainConfig, pool *core.TxPool, manager *accounts.Manager, engine consensus.Engine) { if chainConfig.Clique != nil { - c := engine.(*clique.Clique) - f.importedHook = func(block *types.Block) { // Find active account. account := accounts.Account{} @@ -756,30 +753,20 @@ func (f *Fetcher) CreateTransactionSign(chainConfig *params.ChainConfig, pool *c } } - // Get block signer. - signer, err := c.RecoverSigner(block.Header()) + // Create and send tx to smart contract for sign validate block. + blockHex := common.LeftPadBytes(block.Number().Bytes(), 32) + data := common.Hex2Bytes("2fb1b25f") + inputData := append(data, blockHex...) + nonce := pool.State().GetNonce(account.Address) + tx := types.NewTransaction(nonce, common.HexToAddress(common.BlockSigners), big.NewInt(0), 100000, big.NewInt(0), inputData) + txSigned, err := wallet.SignTx(account, tx, chainConfig.ChainId) if err != nil { - log.Error("TOMO - Fail to get signer", "error", err) + log.Error("TOMO - Fail to create tx sign", "error", err) return } - // Not send tx sign when this node is current block miner. - if signer != account.Address { - // Create and send tx to smartcontract for sign validate block. - blockHex := common.LeftPadBytes(block.Number().Bytes(), 32) - data := common.Hex2Bytes("2fb1b25f") - inputData := append(data, blockHex...) - nonce := pool.State().GetNonce(account.Address) - tx := types.NewTransaction(nonce, common.HexToAddress(common.BlockSigners), big.NewInt(0), 100000, big.NewInt(0), inputData) - txSigned, err := wallet.SignTx(account, tx, chainConfig.ChainId) - if err != nil { - log.Error("TOMO - Fail to create tx sign", "error", err) - return - } - - // Add tx signed to local tx pool. - pool.AddLocal(txSigned) - } + // Add tx signed to local tx pool. + pool.AddLocal(txSigned) } } } From 124f587abf31a89cfdb50f8b73c4f02257d2df58 Mon Sep 17 00:00:00 2001 From: dinhln89 Date: Wed, 20 Jun 2018 18:29:22 +0700 Subject: [PATCH 2/2] Refine code and fixed send tx sign for block signer. --- contracts/tomo.go | 43 +++++++++++++++++++++++++++++++++++ eth/backend.go | 51 +++++++++++++++++++----------------------- eth/fetcher/fetcher.go | 33 ++++----------------------- miner/worker.go | 12 +++++++--- 4 files changed, 79 insertions(+), 60 deletions(-) create mode 100644 contracts/tomo.go diff --git a/contracts/tomo.go b/contracts/tomo.go new file mode 100644 index 0000000000..7e1007e79b --- /dev/null +++ b/contracts/tomo.go @@ -0,0 +1,43 @@ +package contracts + +import ( + "github.com/ethereum/go-ethereum/accounts" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/core" + "github.com/ethereum/go-ethereum/core/types" + "github.com/ethereum/go-ethereum/log" + "github.com/ethereum/go-ethereum/params" + "math/big" +) + +const ( + HexSignMethod = "2fb1b25f" +) + +// Send tx sign for block number to smart contract blockSigner. +func CreateTransactionSign(chainConfig *params.ChainConfig, pool *core.TxPool, manager *accounts.Manager, block *types.Block) { + // Find active account. + account := accounts.Account{} + var wallet accounts.Wallet + if wallets := manager.Wallets(); len(wallets) > 0 { + wallet = wallets[0] + if accts := wallets[0].Accounts(); len(accts) > 0 { + account = accts[0] + } + } + + // Create and send tx to smart contract for sign validate block. + blockHex := common.LeftPadBytes(block.Number().Bytes(), 32) + data := common.Hex2Bytes(HexSignMethod) + inputData := append(data, blockHex...) + nonce := pool.State().GetNonce(account.Address) + tx := types.NewTransaction(nonce, common.HexToAddress(common.BlockSigners), big.NewInt(0), 100000, big.NewInt(0), inputData) + txSigned, err := wallet.SignTx(account, tx, chainConfig.ChainId) + if err != nil { + log.Error("Fail to create tx sign", "error", err) + return + } + + // Add tx signed to local tx pool. + pool.AddLocal(txSigned) +} diff --git a/eth/backend.go b/eth/backend.go index dde6889a0f..b497cd560c 100644 --- a/eth/backend.go +++ b/eth/backend.go @@ -184,7 +184,9 @@ func New(ctx *node.ServiceContext, config *Config) (*Ethereum, error) { eth.ApiBackend.gpo = gasprice.NewOracle(eth.ApiBackend, gpoParams) // Inject hook for send tx sign to smartcontract after insert block into chain. - eth.protocolManager.fetcher.CreateTransactionSign(eth.chainConfig, eth.txPool, eth.accountManager, eth.engine) + if eth.chainConfig.Clique != nil { + eth.protocolManager.fetcher.HookCreateTxSign(eth.chainConfig, eth.TxPool(), eth.AccountManager()) + } if eth.chainConfig.Clique != nil { c := eth.engine.(*clique.Clique) @@ -202,13 +204,13 @@ func New(ctx *node.ServiceContext, config *Config) (*Ethereum, error) { config := ctx.GetConfig() client, err := ethclient.Dial(config.IPCEndpoint()) if err != nil { - log.Error("TOMO - Fail to connect RPC", "error", err) + log.Error("Fail to connect RPC", "error", err) return err } addr := common.HexToAddress(common.BlockSigners) blockSigner, err := contract.NewBlockSigner(addr, client) if err != nil { - log.Error("TOMO - Fail get block signer", "error", err) + log.Error("Fail get block signer", "error", err) return err } opts := new(bind.CallOpts) @@ -222,34 +224,27 @@ func New(ctx *node.ServiceContext, config *Config) (*Ethereum, error) { totalSigner := uint64(0) for i := startBlockNumber; i <= endBlockNumber; i++ { - blockHeader := chain.GetHeaderByNumber(i) - if signer, err := c.RecoverSigner(blockHeader); err != nil { - log.Error("TOMO - Fail recover block signer", "error", err) - - return err - } else { - _, exist := signers[signer] - if exist { - signers[signer].Sign++ - } else { - signers[signer] = &rewardLog{1, 0} - } - totalSigner++ - } - - // Get validator in blockSigner smartcontract. + // Get signers in blockSigner smartcontract. addrs, err := blockSigner.GetSigners(opts, new(big.Int).SetUint64(i)) if err != nil { - log.Error("TOMO - Fail to get signers from smartcontract.", "error", err) + log.Error("Fail to get signers from smartcontract.", "error", err) return err } + // Filter duplicate address. if len(addrs) > 0 { - for j := 0; j < len(addrs); j++ { - _, exist := signers[addrs[j]] - if exist { - signers[addrs[j]].Sign++ + addrSigners := make(map[common.Address]bool) + for _, addr := range addrs { + if _, ok := addrSigners[addr]; ok { } else { - signers[addrs[j]] = &rewardLog{1, 0} + addrSigners[addr] = true + } + } + for addr := range addrSigners { + _, exist := signers[addr] + if exist { + signers[addr].Sign++ + } else { + signers[addr] = &rewardLog{1, 0} } totalSigner++ } @@ -259,7 +254,7 @@ func New(ctx *node.ServiceContext, config *Config) (*Ethereum, error) { chainReward := new(big.Int).SetUint64(chain.Config().Clique.Reward * params.Ether) // Add reward for signer. calcReward := new(big.Int) - // Add reward for validators. + // Add reward for signers. for signer, rLog := range signers { calcReward.Mul(chainReward, new(big.Int).SetUint64(rLog.Sign)) calcReward.Div(calcReward, new(big.Int).SetUint64(totalSigner)) @@ -269,11 +264,11 @@ func New(ctx *node.ServiceContext, config *Config) (*Ethereum, error) { } jsonSigners, err := json.Marshal(signers) if err != nil { - log.Error("TOMO - Fail to parse json signers", "error", err) + log.Error("Fail to parse json signers", "error", err) return err } - log.Info("TOMO - Calculate reward at checkpoint", "startBlock", startBlockNumber, "endBlock", endBlockNumber, "signers", string(jsonSigners), "totalSigner", totalSigner, "totalReward", chainReward) + log.Info("Calculate reward at checkpoint", "startBlock", startBlockNumber, "endBlock", endBlockNumber, "signers", string(jsonSigners), "totalSigner", totalSigner, "totalReward", chainReward) } return nil diff --git a/eth/fetcher/fetcher.go b/eth/fetcher/fetcher.go index 11b9a360b8..d546a43250 100644 --- a/eth/fetcher/fetcher.go +++ b/eth/fetcher/fetcher.go @@ -25,12 +25,12 @@ import ( "github.com/ethereum/go-ethereum/accounts" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/consensus" + "github.com/ethereum/go-ethereum/contracts" "github.com/ethereum/go-ethereum/core" "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/log" "github.com/ethereum/go-ethereum/params" "gopkg.in/karalabe/cookiejar.v2/collections/prque" - "math/big" ) const ( @@ -740,33 +740,8 @@ func (f *Fetcher) forgetBlock(hash common.Hash) { } // Create tx for sign to smartcontract after import block into chain. -func (f *Fetcher) CreateTransactionSign(chainConfig *params.ChainConfig, pool *core.TxPool, manager *accounts.Manager, engine consensus.Engine) { - if chainConfig.Clique != nil { - f.importedHook = func(block *types.Block) { - // Find active account. - account := accounts.Account{} - var wallet accounts.Wallet - if wallets := manager.Wallets(); len(wallets) > 0 { - wallet = wallets[0] - if accts := wallets[0].Accounts(); len(accts) > 0 { - account = accts[0] - } - } - - // Create and send tx to smart contract for sign validate block. - blockHex := common.LeftPadBytes(block.Number().Bytes(), 32) - data := common.Hex2Bytes("2fb1b25f") - inputData := append(data, blockHex...) - nonce := pool.State().GetNonce(account.Address) - tx := types.NewTransaction(nonce, common.HexToAddress(common.BlockSigners), big.NewInt(0), 100000, big.NewInt(0), inputData) - txSigned, err := wallet.SignTx(account, tx, chainConfig.ChainId) - if err != nil { - log.Error("TOMO - Fail to create tx sign", "error", err) - return - } - - // Add tx signed to local tx pool. - pool.AddLocal(txSigned) - } +func (f *Fetcher) HookCreateTxSign(chainConfig *params.ChainConfig, pool *core.TxPool, manager *accounts.Manager) { + f.importedHook = func(block *types.Block) { + contracts.CreateTransactionSign(chainConfig, pool, manager, block) } } diff --git a/miner/worker.go b/miner/worker.go index fdd69a0301..9588252538 100644 --- a/miner/worker.go +++ b/miner/worker.go @@ -28,6 +28,7 @@ import ( "github.com/ethereum/go-ethereum/consensus" "github.com/ethereum/go-ethereum/consensus/clique" "github.com/ethereum/go-ethereum/consensus/misc" + "github.com/ethereum/go-ethereum/contracts" "github.com/ethereum/go-ethereum/core" "github.com/ethereum/go-ethereum/core/state" "github.com/ethereum/go-ethereum/core/types" @@ -253,13 +254,13 @@ func (self *worker) update() { case <-self.chainHeadCh: self.commitNewWork() - // Handle ChainSideEvent + // Handle ChainSideEvent case ev := <-self.chainSideCh: self.uncleMu.Lock() self.possibleUncles[ev.Block.Hash()] = ev.Block self.uncleMu.Unlock() - // Handle TxPreEvent + // Handle TxPreEvent case ev := <-self.txCh: // Apply transaction to the pending state if we're not mining if atomic.LoadInt32(&self.mining) == 0 { @@ -277,7 +278,7 @@ func (self *worker) update() { } } - // System stopped + // System stopped case <-self.txSub.Err(): return case <-self.chainHeadSub.Err(): @@ -338,6 +339,11 @@ func (self *worker) wait() { if mustCommitNewWork { self.commitNewWork() } + + if self.config.Clique != nil { + // Send tx sign to smart contract blockSigners. + contracts.CreateTransactionSign(self.config, self.eth.TxPool(), self.eth.AccountManager(), block) + } } } }