From 25c023758ca5e199483a502bd0c33e1060f92c43 Mon Sep 17 00:00:00 2001 From: Your Name Date: Mon, 17 Dec 2018 18:14:40 +0800 Subject: [PATCH 1/2] modify comment --- cmd/utils/flags.go | 1 - common/compiler/solidity.go | 3 - common/compiler/solidity_test.go | 2 +- consensus/cbft/api.go | 2 +- consensus/cbft/cbft.go | 4 +- consensus/cbft/consensus_cache.go | 22 +++--- consensus/cbft/dpos.go | 20 +++--- consensus/cbft/rotating.go | 16 ++--- consensus/consensus.go | 11 +-- core/cbfttypes/type.go | 4 +- core/chain_indexer.go | 4 -- core/state/state_object.go | 17 +---- eth/downloader/downloader.go | 2 +- ethdb/database.go | 2 +- event/feed.go | 2 +- miner/worker.go | 27 ++++---- params/protocol_params.go | 2 +- rlp/encode_test.go | 8 +-- tests/study/training_lesson.go | 103 ---------------------------- tests/study/training_lesson_test.go | 39 ----------- trie/encoding.go | 2 +- 21 files changed, 65 insertions(+), 228 deletions(-) delete mode 100644 tests/study/training_lesson.go delete mode 100644 tests/study/training_lesson_test.go diff --git a/cmd/utils/flags.go b/cmd/utils/flags.go index c08569f838..6c8dd57bd9 100644 --- a/cmd/utils/flags.go +++ b/cmd/utils/flags.go @@ -1262,7 +1262,6 @@ func SetDashboardConfig(ctx *cli.Context, cfg *dashboard.Config) { // RegisterEthService adds an Ethereum client to the stack. func RegisterEthService(stack *node.Node, cfg *eth.Config) { var err error - // 注册即为定义构造函数的实现方式 if cfg.SyncMode == downloader.LightSync { err = stack.Register(func(ctx *node.ServiceContext) (node.Service, error) { return les.New(ctx, cfg) diff --git a/common/compiler/solidity.go b/common/compiler/solidity.go index 7ae4f9e025..f6e8d2e42a 100644 --- a/common/compiler/solidity.go +++ b/common/compiler/solidity.go @@ -14,7 +14,6 @@ // You should have received a copy of the GNU Lesser General Public License // along with the go-ethereum library. If not, see . -// 对solc的一个包装啦啦啦啦 // Package compiler wraps the Solidity compiler executable (solc). package compiler @@ -69,7 +68,6 @@ type solcOutput struct { Version string } -// 构建命令参数 func (s *Solidity) makeArgs() []string { p := []string{ "--combined-json", "bin,abi,userdoc,devdoc", @@ -93,7 +91,6 @@ func SolidityVersion(solc string) (*Solidity, error) { if err != nil { return nil, err } - // 正则表达式取匹配部分 matches := versionRegexp.FindStringSubmatch(out.String()) if len(matches) != 4 { return nil, fmt.Errorf("can't parse solc version %q", out.String()) diff --git a/common/compiler/solidity_test.go b/common/compiler/solidity_test.go index aaf54c4cb0..fce9c9adaa 100644 --- a/common/compiler/solidity_test.go +++ b/common/compiler/solidity_test.go @@ -78,7 +78,7 @@ func TestCompileError(t *testing.T) { func TestSolidityVersion(t *testing.T) { solidity, err := SolidityVersion("solc") - t.Log("哈哈哈哈,这是单元测试") + t.Log("Hahahaha, this is unit test") if err != nil { t.Log("error throws.", err) } else { diff --git a/consensus/cbft/api.go b/consensus/cbft/api.go index 1b68ca82ed..cb54020ec7 100644 --- a/consensus/cbft/api.go +++ b/consensus/cbft/api.go @@ -13,7 +13,7 @@ type API struct { cbft *Cbft } -// 获取出块人地址 +// Get the block address of producer. func (api *API) GetProducer(number *rpc.BlockNumber) (common.Address, error) { // Retrieve the requested block number (or current if none requested) var header *types.Header diff --git a/consensus/cbft/cbft.go b/consensus/cbft/cbft.go index d371c7c9ec..2c6fd2bbcd 100644 --- a/consensus/cbft/cbft.go +++ b/consensus/cbft/cbft.go @@ -759,7 +759,7 @@ func (cbft *Cbft) signReceiver(sig *cbfttypes.BlockSignature) error { cbft.saveBlock(sig.Hash, ext) } else if ext.isStored { - //收到已经确认块的签名,直接扔掉 + // Receive the signature of the confirmed block and throw it away directly. log.Debug("received a highestConfirmed block's signature, just discard it") return nil } @@ -952,7 +952,7 @@ func (b *Cbft) Prepare(chain consensus.ChainReader, header *types.Header) error cbft.lock.RLock() defer cbft.lock.RUnlock() - //检查父区块 + // Check the parent block if cbft.highestLogical.block == nil || header.ParentHash != cbft.highestLogical.block.Hash() || header.Number.Uint64()-1 != cbft.highestLogical.block.NumberU64() { return consensus.ErrUnknownAncestor } diff --git a/consensus/cbft/consensus_cache.go b/consensus/cbft/consensus_cache.go index 9df05a7941..6e7bc68262 100644 --- a/consensus/cbft/consensus_cache.go +++ b/consensus/cbft/consensus_cache.go @@ -41,7 +41,7 @@ func NewCache(blockChain *core.BlockChain) *Cache { return cache } -// 从缓存map中读取Receipt集合 +// Read the Receipt collection from the cache map. func (c *Cache) ReadReceipts(blockHash common.Hash) []*types.Receipt { c.receiptsMu.RLock() defer c.receiptsMu.RUnlock() @@ -51,7 +51,7 @@ func (c *Cache) ReadReceipts(blockHash common.Hash) []*types.Receipt { return nil } -// 从缓存map中读取StateDB实例 +// Read the StateDB instance from the cache map. func (c *Cache) ReadStateDB(stateRoot common.Hash) *state.StateDB { c.stateDBMu.RLock() defer c.stateDBMu.RUnlock() @@ -61,7 +61,7 @@ func (c *Cache) ReadStateDB(stateRoot common.Hash) *state.StateDB { return nil } -// 将Receipt写入缓存 +// Write Receipt to the cache. func (c *Cache) WriteReceipts(blockHash common.Hash, receipts []*types.Receipt, blockNum uint64) { c.receiptsMu.Lock() defer c.receiptsMu.Unlock() @@ -73,7 +73,7 @@ func (c *Cache) WriteReceipts(blockHash common.Hash, receipts []*types.Receipt, } } -// 将StateDB实例写入缓存 +// Write StateDB instance to the cache. func (c *Cache) WriteStateDB(stateRoot common.Hash, stateDB *state.StateDB, blockNum uint64) { c.stateDBMu.Lock() defer c.stateDBMu.Unlock() @@ -82,7 +82,7 @@ func (c *Cache) WriteStateDB(stateRoot common.Hash, stateDB *state.StateDB, bloc } } -// 从缓存map中读取Receipt集合 +// Read the Receipt collection from the cache map. func (c *Cache) clearReceipts(blockHash common.Hash) { c.receiptsMu.Lock() defer c.receiptsMu.Unlock() @@ -99,7 +99,7 @@ func (c *Cache) clearReceipts(blockHash common.Hash) { } } -// 从缓存map中读取StateDB实例 +// Read the statedb instance from the cache map. func (c *Cache) clearStateDB(stateRoot common.Hash) { c.stateDBMu.Lock() defer c.stateDBMu.Unlock() @@ -116,14 +116,14 @@ func (c *Cache) clearStateDB(stateRoot common.Hash) { } } -// 获取相应block的StateDB实例 +// Get the StateDB instance of the corresponding block. func (c *Cache) MakeStateDB(block *types.Block) (*state.StateDB, error) { - // 基于stateRoot从blockchain中创建StateDB实例 + // Create a StateDB instance from the blockchain based on stateRoot. if state, err := c.chain.StateAt(block.Root()); err == nil && state != nil { return state, nil } - // 读取并拷贝缓存中StateDB实例 - log.Info("读取并拷贝缓存中StateDB实例", "stateRoot", block.Root()) + // Read and copy the stateDB instance in the cache. + log.Info("~ Read and copy the stateDB instance in the cache.", "stateRoot", block.Root()) if state := c.ReadStateDB(block.Root()); state != nil { return state.Copy(), nil } else { @@ -131,7 +131,7 @@ func (c *Cache) MakeStateDB(block *types.Block) (*state.StateDB, error) { } } -// 获取相应block的StateDB实例 +// Get the StateDB instance of the corresponding block. func (c *Cache) ClearCache(block *types.Block) { c.clearReceipts(block.Hash()) c.clearStateDB(block.Root()) diff --git a/consensus/cbft/dpos.go b/consensus/cbft/dpos.go index 6a7d6bde17..f865f1e0ef 100644 --- a/consensus/cbft/dpos.go +++ b/consensus/cbft/dpos.go @@ -13,7 +13,9 @@ type dpos struct { primaryNodeList []discover.NodeID chain *core.BlockChain lastCycleBlockNum uint64 - startTimeOfEpoch int64 // 一轮共识开始时间,通常是上一轮共识结束时最后一个区块的出块时间;如果是第一轮,则从1970.1.1.0.0.0.0开始。单位:秒 + startTimeOfEpoch int64 // A round of consensus start time is usually the block time + // of the last block at the end of the last round of consensus; + // if it is the first round, it starts from 1970.1.1.0.0.0.0. Unit: second } @@ -25,8 +27,8 @@ func newDpos(initialNodes []discover.NodeID) *dpos { return dpos } +// Determine whether the current node is a consensus node. func (d *dpos) IsPrimary(addr common.Address) bool { - // 判断当前节点是否是共识节点 for _, node := range d.primaryNodeList { pub, err := node.Pubkey() if err != nil || pub == nil { @@ -48,21 +50,21 @@ func (d *dpos) NodeIndex(nodeID discover.NodeID) int64 { } func (d *dpos) LastCycleBlockNum() uint64 { - // 获取最后一轮共识结束时的区块高度 + // Get the block height at the end of the final round of consensus. return d.lastCycleBlockNum } func (d *dpos) SetLastCycleBlockNum(blockNumber uint64) { - // 设置最后一轮共识结束时的区块高度 + // Set the block height at the end of the last round of consensus d.lastCycleBlockNum = blockNumber } -// 返回当前共识节点地址列表 +// Returns the current consensus node address list. /*func (b *dpos) ConsensusNodes() []discover.Node { return b.primaryNodeList } */ -// 判断某个节点是否本轮或上一轮选举共识节点 +// Determine whether a node is the current or previous round of election consensus nodes. /*func (b *dpos) CheckConsensusNode(id discover.NodeID) bool { nodes := b.ConsensusNodes() for _, node := range nodes { @@ -73,7 +75,7 @@ func (d *dpos) SetLastCycleBlockNum(blockNumber uint64) { return false }*/ -// 判断当前节点是否本轮或上一轮选举共识节点 +// Determine whether the current node is the current or previous round of election consensus nodes. /*func (b *dpos) IsConsensusNode() (bool, error) { return true, nil } @@ -84,7 +86,7 @@ func (d *dpos) StartTimeOfEpoch() int64 { } func (d *dpos) SetStartTimeOfEpoch(startTimeOfEpoch int64) { - // 设置最后一轮共识结束时的出块时间 + // Set the block time at the end of the last round of consensus. d.startTimeOfEpoch = startTimeOfEpoch - log.Info("设置最后一轮共识结束时的出块时间", "startTimeOfEpoch", startTimeOfEpoch) + log.Info("~ Set the block time at the end of the last round of consensus.", "startTimeOfEpoch", startTimeOfEpoch) } diff --git a/consensus/cbft/rotating.go b/consensus/cbft/rotating.go index 9207ec242b..f37c29632c 100644 --- a/consensus/cbft/rotating.go +++ b/consensus/cbft/rotating.go @@ -6,10 +6,10 @@ import ( type rotating struct { dpos *dpos - rotaList []common.Address // 本轮循环出块节点顺序列表 - startTime int64 // 本轮循环开始时间戳,单位毫秒 - endTime int64 // 本轮循环结束时间戳,单位毫秒 - timeInterval int64 // 每个节点出块时间,单位毫秒 + rotaList []common.Address // This round of cyclic block node order list + startTime int64 // The current cycle start timestamp, in milliseconds + endTime int64 // The current cycle end timestamp, in milliseconds + timeInterval int64 // Block time per unit, in milliseconds } func newRotating(dpos *dpos, timeInterval int64) *rotating { @@ -21,13 +21,13 @@ func newRotating(dpos *dpos, timeInterval int64) *rotating { } func sort() { - // 新一轮共识的排序函数 - // xor(上一轮的最后区块hash + 节点公钥地址) + // New round of consensus sorting function + // xor(Last block last block hash + node public key address) } func (r *rotating) IsRotating(common.Address) bool { - // 判断当前节点是否轮值出块 - // 根据共识排序以及时间窗口 + // Determine whether the current node is out of order + // Sort by consensus and time window return false } diff --git a/consensus/consensus.go b/consensus/consensus.go index 469062db72..959cde4502 100644 --- a/consensus/consensus.go +++ b/consensus/consensus.go @@ -120,14 +120,14 @@ type PoW interface { type Bft interface { Engine - // 返回当前共识节点地址列表 + // Returns the current consensus node address list. ConsensusNodes() ([]discover.NodeID, error) - // 返回当前节点是否轮值出块 + // Returns whether the current node is out of the block. ShouldSeal() (bool, error) - //收到新的区块签名 - //需要验证签名是否时nodeID签名的 + // Received a new block signature + // Need to verify if the signature is signed by nodeID OnBlockSignature(chain ChainReader, nodeID discover.NodeID, sig *cbfttypes.BlockSignature) error // Process the BFT signatures @@ -140,7 +140,8 @@ type Bft interface { IsConsensusNode() (bool, error) - //目前最高的合理块,本节点出块时,需要基于最高合理块来生成区块。 + // At present, the highest reasonable block, when the node is out of the block, + // it needs to generate the block based on the highest reasonable block. HighestLogicalBlock() *types.Block SetPrivateKey(privateKey *ecdsa.PrivateKey) diff --git a/core/cbfttypes/type.go b/core/cbfttypes/type.go index f7e2c54df8..7aeec1c28f 100644 --- a/core/cbfttypes/type.go +++ b/core/cbfttypes/type.go @@ -8,8 +8,8 @@ import ( // Block's Signature info type BlockSignature struct { - SignHash common.Hash //签名hash,header[0:32] - Hash common.Hash //块hash,header[:] + SignHash common.Hash // signature hash,header[0:32] + Hash common.Hash // block hash,header[:] Number *big.Int Signature *common.BlockConfirmSign } diff --git a/core/chain_indexer.go b/core/chain_indexer.go index b4c6745556..e8a4653d94 100644 --- a/core/chain_indexer.go +++ b/core/chain_indexer.go @@ -32,23 +32,19 @@ import ( "github.com/PlatONnetwork/PlatON-Go/log" ) -// 定义了处理区块链片段的方法,并把处理结果写入数据库 // ChainIndexerBackend defines the methods needed to process chain segments in // the background and write the segment results into the database. These can be // used to create filter blooms or CHTs. type ChainIndexerBackend interface { - // 用来初始化一个新的区块链片段,可能会终止任何没有完成的操作 // Reset initiates the processing of a new chain segment, potentially terminating // any partially completed operations (in case of a reorg). Reset(ctx context.Context, section uint64, prevHead common.Hash) error - // 对区块链片段中的下一个区块头进行处理。 调用者将确保区块头的连续顺序 // Process crunches through the next header in the chain segment. The caller // will ensure a sequential order of headers. Process(ctx context.Context, header *types.Header) error - // 完成区块链片段的元数据并将其存储到数据库中 // Commit finalizes the section metadata and stores it into the database. Commit() error } diff --git a/core/state/state_object.go b/core/state/state_object.go index ee78e38443..7f3afc5e3c 100644 --- a/core/state/state_object.go +++ b/core/state/state_object.go @@ -28,9 +28,6 @@ import ( "github.com/PlatONnetwork/PlatON-Go/rlp" ) -// account对象的抽象,提供了账户的一些功能。 -// 表示正在修改的以太坊账户 - var emptyCodeHash = crypto.Keccak256(nil) type Code []byte @@ -43,20 +40,17 @@ func (self Code) String() string { type Storage map[string]common.Hash type ValueStorage map[common.Hash][]byte -// 该结构:用于缓存智能合约中所有变量的值 // Storage -> hash : hash , common.Hash ([32]byte) //type Storage map[common.Hash]common.Hash func (self Storage) String() (str string) { for key, value := range self { - // %X -> 提供16进制 str += fmt.Sprintf("%X : %X\n", key, value) } return } -// 复制一份Storage func (self Storage) Copy() Storage { cpy := make(Storage) for key, value := range self { @@ -92,7 +86,6 @@ type stateObject struct { // unable to deal with database-level errors. Any error that occurs // during a database read is memoized here and will eventually be returned // by StateDB.Commit. - // 当一个对象被标记为自杀时,它将在状态转换的“更新”阶段期间从树中删除。 dbErr error // Write caches. @@ -100,7 +93,6 @@ type stateObject struct { // storage trie, which becomes non-nil on first access code Code // contract bytecode, which gets set when code is loaded - // todo: 新增,此字段尚不明确是否需要进行使用 abi Abi originStorage Storage // Storage cache of original entries to dedup rewrites @@ -124,13 +116,11 @@ func (s *stateObject) empty() bool { // Account is the Ethereum consensus representation of accounts. // These objects are stored in the main account trie. -// 帐户是以太坊共识表示的帐户。 这些对象存储在main account trie。 type Account struct { Nonce uint64 Balance *big.Int Root common.Hash // merkle root of the storage trie CodeHash []byte - // todo: 新增AbiHash字段 AbiHash []byte } @@ -287,7 +277,7 @@ func (self *stateObject) GetCommittedState(db Database, key string) []byte { func (self *stateObject) SetState(db Database, keyTrie string, valueKey common.Hash, value []byte) { //if the new value is the same as old,don't set - preValue := self.GetState(db, keyTrie) //获取value key + preValue := self.GetState(db, keyTrie) //get value key if bytes.Equal(preValue, value) { return } @@ -327,7 +317,6 @@ func (self *stateObject) updateTrie(db Database) Trie { delete(self.dirtyStorage, key) delete(self.dirtyValueStorage, valueKey) - //删除原来valueKey 对应的value delete(self.originValueStorage, self.originStorage[key]) self.originStorage[key] = valueKey @@ -499,9 +488,6 @@ func (self *stateObject) Value() *big.Int { panic("Value on stateObject should never be called") } -// todo: 新增方法 -// ======================================= 新增方法 =============================== - // todo: new method -> AbiHash func (self *stateObject) AbiHash() []byte { return self.data.AbiHash @@ -515,7 +501,6 @@ func (self *stateObject) Abi(db Database) []byte { if bytes.Equal(self.AbiHash(), emptyCodeHash) { return nil } - // 从树中提取code,入参:地址及hash, 此处需要深入发现获取规则 abi, err := db.ContractAbi(self.addrHash, common.BytesToHash(self.AbiHash())) if err != nil { self.setError(fmt.Errorf("can't load abi hash %x: %v", self.AbiHash(), err)) diff --git a/eth/downloader/downloader.go b/eth/downloader/downloader.go index eaf3056dc1..2d54fe4cb8 100644 --- a/eth/downloader/downloader.go +++ b/eth/downloader/downloader.go @@ -315,7 +315,7 @@ func (d *Downloader) UnregisterPeer(id string) error { // Synchronise tries to sync up our local block chain with a remote peer, both // adding various sanity checks as well as wrapping it with various log entries. func (d *Downloader) Synchronise(id string, head common.Hash, td *big.Int, mode SyncMode) error { - log.Warn("----------向对端节点同步区块数据----------", "peerID", id, "head", head, "td", td, "mode", mode) + log.Warn("~ Synchronize block data to the peer node", "peerID", id, "head", head, "td", td, "mode", mode) err := d.synchronise(id, head, td, mode) switch err { case nil: diff --git a/ethdb/database.go b/ethdb/database.go index 1848b5f5fa..33e9c3c89d 100644 --- a/ethdb/database.go +++ b/ethdb/database.go @@ -70,7 +70,7 @@ func NewLDBDatabase(file string, cache int, handles int) (*LDBDatabase, error) { } logger.Info("Allocated cache and file handles", "cache", cache, "handles", handles) - // 构建DB对象 + // Build DB instance. // Open the db and recover any potential corruptions db, err := leveldb.OpenFile(file, &opt.Options{ OpenFilesCacheCapacity: handles, diff --git a/event/feed.go b/event/feed.go index ffcf5fa950..f578f00c10 100644 --- a/event/feed.go +++ b/event/feed.go @@ -25,7 +25,7 @@ import ( var errBadChannel = errors.New("event: Subscribe argument does not have sendable channel type") // Feed implements one-to-many subscriptions where the carrier of events is a channel. -// Values sent to a Feed are delivered to all subscribed channels simultaneously.(同时的) +// Values sent to a Feed are delivered to all subscribed channels simultaneously. // // Feeds can only be used with a single type. The type is determined by the first Send or // Subscribe operation. Subsequent calls to these methods panic if the type does not diff --git a/miner/worker.go b/miner/worker.go index 9366184938..2f3c66f35b 100644 --- a/miner/worker.go +++ b/miner/worker.go @@ -164,8 +164,8 @@ type worker struct { taskCh chan *task resultCh chan *types.Block prepareResultCh chan *types.Block - blockSignatureCh chan *cbfttypes.BlockSignature // 签名 - cbftResultCh chan *cbfttypes.CbftResult // Seal出块后输出的channel + blockSignatureCh chan *cbfttypes.BlockSignature // signature + cbftResultCh chan *cbfttypes.CbftResult // Seal block and output to channel highestLogicalBlockCh chan *types.Block startCh chan struct{} exitCh chan struct{} @@ -410,7 +410,7 @@ func (w *worker) newWorkLoop(recommit time.Duration) { w.consensusCache.ClearCache(head.Block) case highestLogicalBlock := <-w.highestLogicalBlockCh: - log.Info("highestLogicalBlockCh通道接收数据", "number", highestLogicalBlock.NumberU64(), "hash", highestLogicalBlock.Hash()) + log.Info("highestLogicalBlockCh - Channel receiving data", "number", highestLogicalBlock.NumberU64(), "hash", highestLogicalBlock.Hash()) w.commitWorkEnv.highestLock.Lock() w.commitWorkEnv.highestLogicalBlock = highestLogicalBlock w.commitWorkEnv.highestLock.Unlock() @@ -418,7 +418,7 @@ func (w *worker) newWorkLoop(recommit time.Duration) { if w.isRunning() { if shouldSeal, error := w.engine.(consensus.Bft).ShouldSeal(); shouldSeal && error == nil { if shouldCommit, commitBlock := w.shouldCommit(time.Now().UnixNano() / 1e6); shouldCommit { - log.Warn("--------------highestLogicalBlock增长,并且间隔" + recommit.String() + "未执行打包任务,执行打包出块逻辑--------------") + log.Warn("~ HighestLogicalBlock increase, And interval " + recommit.String() + " Package task not executed,Execute packed out logic.") commit(false, commitInterruptResubmit, commitBlock) } } @@ -427,13 +427,12 @@ func (w *worker) newWorkLoop(recommit time.Duration) { case <-timer.C: // If mining is running resubmit a new work cycle periodically to pull in // higher priced transactions. Disable this overhead for pending blocks. - // timer控制,间隔recommit seconds进行出块,如果是cbft共识允许出空块 if w.isRunning() { - log.Warn("----------间隔" + recommit.String() + "开始打包任务----------") + log.Warn("~ Interval" + recommit.String() + " to start packing tasks.") if cbftEngine, ok := w.engine.(consensus.Bft); ok { if shouldSeal, error := cbftEngine.ShouldSeal(); shouldSeal && error == nil { if shouldCommit, commitBlock := w.shouldCommit(time.Now().UnixNano() / 1e6); shouldCommit { - log.Warn("--------------节点当前时间窗口出块,执行打包出块逻辑--------------") + log.Warn("~ The current time window of the node is out of the block, and the packaged block logic is executed.") commit(false, commitInterruptResubmit, commitBlock) continue } @@ -450,7 +449,7 @@ func (w *worker) newWorkLoop(recommit time.Duration) { } case interval := <-w.resubmitIntervalCh: - // cbft引擎不允许外界修改recommit值 + // cbft engine do not allow outside modifications recommit value. if _, ok := w.engine.(consensus.Bft); !ok { // Adjust resubmit interval explicitly by user. if interval < minRecommitInterval { @@ -466,7 +465,7 @@ func (w *worker) newWorkLoop(recommit time.Duration) { } case adjust := <-w.resubmitAdjustCh: - // cbft引擎不需要重新计算调整recommit值 + // cbft engine no need to recalculate adjustments recommit value. if _, ok := w.engine.(consensus.Bft); !ok { // Adjust resubmit interval by feedback. if adjust.inc { @@ -763,7 +762,7 @@ func (w *worker) resultLoop() { _receipts = task.receipts _state = task.state } else { - log.Info("从consensusCache中读取receipts、state", "blockHash", block.Hash(), "stateRoot", block.Root()) + log.Info("~ Read receipts、state from consensusCache", "blockHash", block.Hash(), "stateRoot", block.Root()) _receipts = w.consensusCache.ReadReceipts(block.Hash()) _state = w.consensusCache.ReadStateDB(block.Root()) } @@ -773,7 +772,7 @@ func (w *worker) resultLoop() { continue } - log.Warn("[2]共识成功", "blockNumber", block.NumberU64(), "timestamp", time.Now().UnixNano()/1e6) + log.Warn("[2]Consensus success", "blockNumber", block.NumberU64(), "timestamp", time.Now().UnixNano()/1e6) // Different block could share same sealhash, deep copy here to prevent write-write conflict. var ( @@ -937,7 +936,7 @@ func (w *worker) commitTransactions(txs *types.TransactionsByPriceAndNonce, coin for { if bftEngine && (float64(time.Now().UnixNano()/1e6-timestamp) >= w.commitDuration) { - log.Warn("------执行交易超时,主动退出,继续剩余打包流程------", "超时时长", w.commitDuration, "本轮执行交易数", w.current.tcount) + log.Warn("~ Execute transaction timeout, take the initiative to exit, continue the remaining packaging process", "Timeout period", w.commitDuration, "Number of executed transactions in the current round", w.current.tcount) break } // In the following three cases, we will interrupt the execution of the transaction. @@ -1082,7 +1081,7 @@ func (w *worker) commitNewWork(interrupt *int32, noempty bool, timestamp int64, header.Coinbase = w.coinbase } - log.Warn("[1]共识开始", "gasLimit", header.GasLimit, "blockNumber", header.Number, "timestamp", time.Now().UnixNano()/1e6) + log.Warn("[1]Consensus Start", "gasLimit", header.GasLimit, "blockNumber", header.Number, "timestamp", time.Now().UnixNano()/1e6) if err := w.engine.Prepare(w.chain, header); err != nil { log.Error("Failed to prepare header for mining", "err", err) return @@ -1215,7 +1214,7 @@ func (w *worker) commit(uncles []*types.Header, interval func(), update bool, st } select { case w.taskCh <- &task{receipts: receipts, state: s, block: block, createdAt: time.Now()}: - // 保存receipts、stateDB至缓存 + // save receipts、stateDB to cache. w.consensusCache.WriteReceipts(block.Hash(), receipts, block.NumberU64()) w.consensusCache.WriteStateDB(block.Root(), s, block.NumberU64()) diff --git a/params/protocol_params.go b/params/protocol_params.go index 36ee97e20c..f47febc30f 100644 --- a/params/protocol_params.go +++ b/params/protocol_params.go @@ -29,7 +29,7 @@ const ( CallValueTransferGas uint64 = 9000 // Paid for CALL when the value transfer is non-zero. CallNewAccountGas uint64 = 25000 // Paid for CALL when the destination address didn't exist prior. TxGas uint64 = 21000 // Per transaction not creating a contract. NOTE: Not payable on data of calls between transactions. - // todo: 而已创建gas需要的值,此处需要处理 pre value: 53000 + // todo: pre value: 53000 TxGasContractCreation uint64 = 453000 // Per transaction that creates a contract. NOTE: Not payable on data of calls between transactions. TxDataZeroGas uint64 = 4 // Per byte of data attached to a transaction that equals zero. NOTE: Not payable on data of calls between transactions. QuadCoeffDiv uint64 = 512 // Divisor for the quadratic particle of the memory cost equation. diff --git a/rlp/encode_test.go b/rlp/encode_test.go index 5b1d73f938..565290832b 100644 --- a/rlp/encode_test.go +++ b/rlp/encode_test.go @@ -291,10 +291,10 @@ func TestEncodeF03(t *testing.T) { fmt.Println(string(res)) //val := []interface{}{"transfer", uint(0xFFFFFF), []interface{}{[]uint{4, 5, 5}}, "abc"} - fmt.Println([]byte("人才是你吗")) + fmt.Println([]byte("Hello")) var source [][]byte source = make([][]byte, 0) - source = append(source, []byte("人才是你吗")) + source = append(source, []byte("Hello")) source = append(source, uint64ToBytes(1000)) source = append(source, uint64ToBytes(2000)) source = append(source, boolToBytes(false)) @@ -306,7 +306,7 @@ func TestEncodeF03(t *testing.T) { fmt.Println(err) t.Errorf("fail") } - // 编码后字节数组 + encodedBytes := buffer.Bytes() fmt.Println(encodedBytes) @@ -317,7 +317,7 @@ func TestEncodeF03(t *testing.T) { fmt.Println(deref) for i, v := range deref.([]interface{}) { // fmt.Println(i," ",hex.EncodeToString(v.([]byte))) - // 类型判断,然后转换 + // Type judgment, then convert switch i { case 0: fmt.Println(string(v.([]byte))) diff --git a/tests/study/training_lesson.go b/tests/study/training_lesson.go deleted file mode 100644 index 4a31cbd354..0000000000 --- a/tests/study/training_lesson.go +++ /dev/null @@ -1,103 +0,0 @@ -package main - -import ( - "fmt" - "net/http" - "os" - "time" -) - -//定义struct,作为http的handler -type MessageHandler struct { - //处理get/post数据的channel - ch chan string -} - -//MessageHandler需要实现ServeHTTP方法,才能正式成为一个handler -func (m *MessageHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { - r.ParseForm() - if len(r.FormValue("message")) > 0 { - fmt.Println("message:", r.FormValue("message")) - fmt.Fprintf(w, r.FormValue("message")) - m.ch <- r.FormValue("message") - } -} - -//启动http server -func startHttpServer(ch chan string, f *os.File) { - //初始化MessageHandler,并注册到http中 - http.Handle("/test", &MessageHandler{ch}) - err := http.ListenAndServe(":8080", nil) - if err != nil { - fmt.Println("http server start error!", err) - return - } -} - -//写文件的loop -func fileWriterLoop(ch chan string, f *os.File) { - - //声明并初始化一个capacity=2的slice - msgBuffer := make([]string, 0, 2) - for { - //从ch中读取数据,并附上换行符,放入slice - msgBuffer = append(msgBuffer, <-ch+"\r\n") - if len(msgBuffer) == 2 { //slice长度==2,则写文件 - for _, msg := range msgBuffer { - //把slice中的字符串,一个个写入文件 - _, err := f.WriteString(msg) - if err != nil { - fmt.Println("write message to file error:", err) - } - } - //重置slice,内容清空,长度设置为0 - msgBuffer = msgBuffer[0:0] - } - } -} - -func main3() { - //声明并初始化一个带buffer的channel - ch := make(chan string, 99) - f, err := os.OpenFile("d:\\test.txt", os.O_RDWR|os.O_CREATE, 0766) - if err != nil { - fmt.Println("open file failed") - return - } - defer f.Close() - - //1st. start fileWriter goroutine - go fileWriterLoop(ch, f) - - //2nd. start receiver goroutine - go startHttpServer(ch, f) - - //waiting.... - time.Sleep(time.Duration(10000) * time.Second) - -} - -func main() { - ch := make(chan int) - param := 3 - var param1 int - go func() { - select { - case param1 = <-ch: - fmt.Printf("received %d from ch\n", param1) - //default: - //fmt.Printf("no communication222\n") - } - }() - - go func() { - select { - case ch <- param: - fmt.Printf("sent %d to ch\n", param) - default: - fmt.Println("no communication111") - } - }() - - time.Sleep(time.Duration(2000)) -} diff --git a/tests/study/training_lesson_test.go b/tests/study/training_lesson_test.go deleted file mode 100644 index 9bc869b860..0000000000 --- a/tests/study/training_lesson_test.go +++ /dev/null @@ -1,39 +0,0 @@ -package main - -import ( - "fmt" - "io/ioutil" - "net/http" - "testing" -) - -const ( - message = "shanghai" -) - -var dataList = []string{"test1", "test2", "test3", "test4", "test5", "test6", "test7", "test8", "test9", "test10"} - -func TestSendMessage(t *testing.T) { - - for _, data := range dataList { - t.Run(fmt.Sprintf("send:%s", data), func(t *testing.T) { - - resp, err := http.Get("http://localhost:8080/test?message=" + data) - - if err != nil { - // handle error - } - defer resp.Body.Close() - - body, err := ioutil.ReadAll(resp.Body) - if err != nil { - // handle error - } - fmt.Println(string(body)) - // 检测返回的数据 - if string(body) != data { - t.Errorf("handler returned unexpected body: got %v want %v", string(body), data) - } - }) - } -} diff --git a/trie/encoding.go b/trie/encoding.go index 1940cef483..f0becb3efa 100644 --- a/trie/encoding.go +++ b/trie/encoding.go @@ -35,7 +35,7 @@ package trie // into the remaining bytes. Compact encoding is used for nodes stored on disk. func hexToCompact(hex []byte) []byte { - terminator := byte(0) // 分隔符 + terminator := byte(0) // Separator if hasTerm(hex) { terminator = 1 hex = hex[:len(hex)-1] From 1c56b7e50ca3b1524213f267625ef3a44478e4bb Mon Sep 17 00:00:00 2001 From: raventrov Date: Mon, 17 Dec 2018 18:28:34 +0800 Subject: [PATCH 2/2] modify comment --- cmd/utils/flags.go | 1 - common/compiler/solidity.go | 3 - common/compiler/solidity_test.go | 2 +- consensus/cbft/api.go | 2 +- consensus/cbft/cbft.go | 4 +- consensus/cbft/consensus_cache.go | 22 +++--- consensus/cbft/dpos.go | 20 +++--- consensus/cbft/rotating.go | 16 ++--- consensus/consensus.go | 11 +-- core/cbfttypes/type.go | 4 +- core/chain_indexer.go | 4 -- core/state/state_object.go | 17 +---- eth/downloader/downloader.go | 2 +- ethdb/database.go | 2 +- event/feed.go | 2 +- miner/worker.go | 27 ++++---- params/protocol_params.go | 2 +- rlp/encode_test.go | 8 +-- tests/study/training_lesson.go | 103 ---------------------------- tests/study/training_lesson_test.go | 39 ----------- trie/encoding.go | 2 +- 21 files changed, 65 insertions(+), 228 deletions(-) delete mode 100644 tests/study/training_lesson.go delete mode 100644 tests/study/training_lesson_test.go diff --git a/cmd/utils/flags.go b/cmd/utils/flags.go index c08569f838..6c8dd57bd9 100644 --- a/cmd/utils/flags.go +++ b/cmd/utils/flags.go @@ -1262,7 +1262,6 @@ func SetDashboardConfig(ctx *cli.Context, cfg *dashboard.Config) { // RegisterEthService adds an Ethereum client to the stack. func RegisterEthService(stack *node.Node, cfg *eth.Config) { var err error - // 注册即为定义构造函数的实现方式 if cfg.SyncMode == downloader.LightSync { err = stack.Register(func(ctx *node.ServiceContext) (node.Service, error) { return les.New(ctx, cfg) diff --git a/common/compiler/solidity.go b/common/compiler/solidity.go index 7ae4f9e025..f6e8d2e42a 100644 --- a/common/compiler/solidity.go +++ b/common/compiler/solidity.go @@ -14,7 +14,6 @@ // You should have received a copy of the GNU Lesser General Public License // along with the go-ethereum library. If not, see . -// 对solc的一个包装啦啦啦啦 // Package compiler wraps the Solidity compiler executable (solc). package compiler @@ -69,7 +68,6 @@ type solcOutput struct { Version string } -// 构建命令参数 func (s *Solidity) makeArgs() []string { p := []string{ "--combined-json", "bin,abi,userdoc,devdoc", @@ -93,7 +91,6 @@ func SolidityVersion(solc string) (*Solidity, error) { if err != nil { return nil, err } - // 正则表达式取匹配部分 matches := versionRegexp.FindStringSubmatch(out.String()) if len(matches) != 4 { return nil, fmt.Errorf("can't parse solc version %q", out.String()) diff --git a/common/compiler/solidity_test.go b/common/compiler/solidity_test.go index aaf54c4cb0..fce9c9adaa 100644 --- a/common/compiler/solidity_test.go +++ b/common/compiler/solidity_test.go @@ -78,7 +78,7 @@ func TestCompileError(t *testing.T) { func TestSolidityVersion(t *testing.T) { solidity, err := SolidityVersion("solc") - t.Log("哈哈哈哈,这是单元测试") + t.Log("Hahahaha, this is unit test") if err != nil { t.Log("error throws.", err) } else { diff --git a/consensus/cbft/api.go b/consensus/cbft/api.go index 1b68ca82ed..cb54020ec7 100644 --- a/consensus/cbft/api.go +++ b/consensus/cbft/api.go @@ -13,7 +13,7 @@ type API struct { cbft *Cbft } -// 获取出块人地址 +// Get the block address of producer. func (api *API) GetProducer(number *rpc.BlockNumber) (common.Address, error) { // Retrieve the requested block number (or current if none requested) var header *types.Header diff --git a/consensus/cbft/cbft.go b/consensus/cbft/cbft.go index d371c7c9ec..2c6fd2bbcd 100644 --- a/consensus/cbft/cbft.go +++ b/consensus/cbft/cbft.go @@ -759,7 +759,7 @@ func (cbft *Cbft) signReceiver(sig *cbfttypes.BlockSignature) error { cbft.saveBlock(sig.Hash, ext) } else if ext.isStored { - //收到已经确认块的签名,直接扔掉 + // Receive the signature of the confirmed block and throw it away directly. log.Debug("received a highestConfirmed block's signature, just discard it") return nil } @@ -952,7 +952,7 @@ func (b *Cbft) Prepare(chain consensus.ChainReader, header *types.Header) error cbft.lock.RLock() defer cbft.lock.RUnlock() - //检查父区块 + // Check the parent block if cbft.highestLogical.block == nil || header.ParentHash != cbft.highestLogical.block.Hash() || header.Number.Uint64()-1 != cbft.highestLogical.block.NumberU64() { return consensus.ErrUnknownAncestor } diff --git a/consensus/cbft/consensus_cache.go b/consensus/cbft/consensus_cache.go index 9df05a7941..6e7bc68262 100644 --- a/consensus/cbft/consensus_cache.go +++ b/consensus/cbft/consensus_cache.go @@ -41,7 +41,7 @@ func NewCache(blockChain *core.BlockChain) *Cache { return cache } -// 从缓存map中读取Receipt集合 +// Read the Receipt collection from the cache map. func (c *Cache) ReadReceipts(blockHash common.Hash) []*types.Receipt { c.receiptsMu.RLock() defer c.receiptsMu.RUnlock() @@ -51,7 +51,7 @@ func (c *Cache) ReadReceipts(blockHash common.Hash) []*types.Receipt { return nil } -// 从缓存map中读取StateDB实例 +// Read the StateDB instance from the cache map. func (c *Cache) ReadStateDB(stateRoot common.Hash) *state.StateDB { c.stateDBMu.RLock() defer c.stateDBMu.RUnlock() @@ -61,7 +61,7 @@ func (c *Cache) ReadStateDB(stateRoot common.Hash) *state.StateDB { return nil } -// 将Receipt写入缓存 +// Write Receipt to the cache. func (c *Cache) WriteReceipts(blockHash common.Hash, receipts []*types.Receipt, blockNum uint64) { c.receiptsMu.Lock() defer c.receiptsMu.Unlock() @@ -73,7 +73,7 @@ func (c *Cache) WriteReceipts(blockHash common.Hash, receipts []*types.Receipt, } } -// 将StateDB实例写入缓存 +// Write StateDB instance to the cache. func (c *Cache) WriteStateDB(stateRoot common.Hash, stateDB *state.StateDB, blockNum uint64) { c.stateDBMu.Lock() defer c.stateDBMu.Unlock() @@ -82,7 +82,7 @@ func (c *Cache) WriteStateDB(stateRoot common.Hash, stateDB *state.StateDB, bloc } } -// 从缓存map中读取Receipt集合 +// Read the Receipt collection from the cache map. func (c *Cache) clearReceipts(blockHash common.Hash) { c.receiptsMu.Lock() defer c.receiptsMu.Unlock() @@ -99,7 +99,7 @@ func (c *Cache) clearReceipts(blockHash common.Hash) { } } -// 从缓存map中读取StateDB实例 +// Read the statedb instance from the cache map. func (c *Cache) clearStateDB(stateRoot common.Hash) { c.stateDBMu.Lock() defer c.stateDBMu.Unlock() @@ -116,14 +116,14 @@ func (c *Cache) clearStateDB(stateRoot common.Hash) { } } -// 获取相应block的StateDB实例 +// Get the StateDB instance of the corresponding block. func (c *Cache) MakeStateDB(block *types.Block) (*state.StateDB, error) { - // 基于stateRoot从blockchain中创建StateDB实例 + // Create a StateDB instance from the blockchain based on stateRoot. if state, err := c.chain.StateAt(block.Root()); err == nil && state != nil { return state, nil } - // 读取并拷贝缓存中StateDB实例 - log.Info("读取并拷贝缓存中StateDB实例", "stateRoot", block.Root()) + // Read and copy the stateDB instance in the cache. + log.Info("~ Read and copy the stateDB instance in the cache.", "stateRoot", block.Root()) if state := c.ReadStateDB(block.Root()); state != nil { return state.Copy(), nil } else { @@ -131,7 +131,7 @@ func (c *Cache) MakeStateDB(block *types.Block) (*state.StateDB, error) { } } -// 获取相应block的StateDB实例 +// Get the StateDB instance of the corresponding block. func (c *Cache) ClearCache(block *types.Block) { c.clearReceipts(block.Hash()) c.clearStateDB(block.Root()) diff --git a/consensus/cbft/dpos.go b/consensus/cbft/dpos.go index 6a7d6bde17..f865f1e0ef 100644 --- a/consensus/cbft/dpos.go +++ b/consensus/cbft/dpos.go @@ -13,7 +13,9 @@ type dpos struct { primaryNodeList []discover.NodeID chain *core.BlockChain lastCycleBlockNum uint64 - startTimeOfEpoch int64 // 一轮共识开始时间,通常是上一轮共识结束时最后一个区块的出块时间;如果是第一轮,则从1970.1.1.0.0.0.0开始。单位:秒 + startTimeOfEpoch int64 // A round of consensus start time is usually the block time + // of the last block at the end of the last round of consensus; + // if it is the first round, it starts from 1970.1.1.0.0.0.0. Unit: second } @@ -25,8 +27,8 @@ func newDpos(initialNodes []discover.NodeID) *dpos { return dpos } +// Determine whether the current node is a consensus node. func (d *dpos) IsPrimary(addr common.Address) bool { - // 判断当前节点是否是共识节点 for _, node := range d.primaryNodeList { pub, err := node.Pubkey() if err != nil || pub == nil { @@ -48,21 +50,21 @@ func (d *dpos) NodeIndex(nodeID discover.NodeID) int64 { } func (d *dpos) LastCycleBlockNum() uint64 { - // 获取最后一轮共识结束时的区块高度 + // Get the block height at the end of the final round of consensus. return d.lastCycleBlockNum } func (d *dpos) SetLastCycleBlockNum(blockNumber uint64) { - // 设置最后一轮共识结束时的区块高度 + // Set the block height at the end of the last round of consensus d.lastCycleBlockNum = blockNumber } -// 返回当前共识节点地址列表 +// Returns the current consensus node address list. /*func (b *dpos) ConsensusNodes() []discover.Node { return b.primaryNodeList } */ -// 判断某个节点是否本轮或上一轮选举共识节点 +// Determine whether a node is the current or previous round of election consensus nodes. /*func (b *dpos) CheckConsensusNode(id discover.NodeID) bool { nodes := b.ConsensusNodes() for _, node := range nodes { @@ -73,7 +75,7 @@ func (d *dpos) SetLastCycleBlockNum(blockNumber uint64) { return false }*/ -// 判断当前节点是否本轮或上一轮选举共识节点 +// Determine whether the current node is the current or previous round of election consensus nodes. /*func (b *dpos) IsConsensusNode() (bool, error) { return true, nil } @@ -84,7 +86,7 @@ func (d *dpos) StartTimeOfEpoch() int64 { } func (d *dpos) SetStartTimeOfEpoch(startTimeOfEpoch int64) { - // 设置最后一轮共识结束时的出块时间 + // Set the block time at the end of the last round of consensus. d.startTimeOfEpoch = startTimeOfEpoch - log.Info("设置最后一轮共识结束时的出块时间", "startTimeOfEpoch", startTimeOfEpoch) + log.Info("~ Set the block time at the end of the last round of consensus.", "startTimeOfEpoch", startTimeOfEpoch) } diff --git a/consensus/cbft/rotating.go b/consensus/cbft/rotating.go index 9207ec242b..f37c29632c 100644 --- a/consensus/cbft/rotating.go +++ b/consensus/cbft/rotating.go @@ -6,10 +6,10 @@ import ( type rotating struct { dpos *dpos - rotaList []common.Address // 本轮循环出块节点顺序列表 - startTime int64 // 本轮循环开始时间戳,单位毫秒 - endTime int64 // 本轮循环结束时间戳,单位毫秒 - timeInterval int64 // 每个节点出块时间,单位毫秒 + rotaList []common.Address // This round of cyclic block node order list + startTime int64 // The current cycle start timestamp, in milliseconds + endTime int64 // The current cycle end timestamp, in milliseconds + timeInterval int64 // Block time per unit, in milliseconds } func newRotating(dpos *dpos, timeInterval int64) *rotating { @@ -21,13 +21,13 @@ func newRotating(dpos *dpos, timeInterval int64) *rotating { } func sort() { - // 新一轮共识的排序函数 - // xor(上一轮的最后区块hash + 节点公钥地址) + // New round of consensus sorting function + // xor(Last block last block hash + node public key address) } func (r *rotating) IsRotating(common.Address) bool { - // 判断当前节点是否轮值出块 - // 根据共识排序以及时间窗口 + // Determine whether the current node is out of order + // Sort by consensus and time window return false } diff --git a/consensus/consensus.go b/consensus/consensus.go index 469062db72..959cde4502 100644 --- a/consensus/consensus.go +++ b/consensus/consensus.go @@ -120,14 +120,14 @@ type PoW interface { type Bft interface { Engine - // 返回当前共识节点地址列表 + // Returns the current consensus node address list. ConsensusNodes() ([]discover.NodeID, error) - // 返回当前节点是否轮值出块 + // Returns whether the current node is out of the block. ShouldSeal() (bool, error) - //收到新的区块签名 - //需要验证签名是否时nodeID签名的 + // Received a new block signature + // Need to verify if the signature is signed by nodeID OnBlockSignature(chain ChainReader, nodeID discover.NodeID, sig *cbfttypes.BlockSignature) error // Process the BFT signatures @@ -140,7 +140,8 @@ type Bft interface { IsConsensusNode() (bool, error) - //目前最高的合理块,本节点出块时,需要基于最高合理块来生成区块。 + // At present, the highest reasonable block, when the node is out of the block, + // it needs to generate the block based on the highest reasonable block. HighestLogicalBlock() *types.Block SetPrivateKey(privateKey *ecdsa.PrivateKey) diff --git a/core/cbfttypes/type.go b/core/cbfttypes/type.go index f7e2c54df8..7aeec1c28f 100644 --- a/core/cbfttypes/type.go +++ b/core/cbfttypes/type.go @@ -8,8 +8,8 @@ import ( // Block's Signature info type BlockSignature struct { - SignHash common.Hash //签名hash,header[0:32] - Hash common.Hash //块hash,header[:] + SignHash common.Hash // signature hash,header[0:32] + Hash common.Hash // block hash,header[:] Number *big.Int Signature *common.BlockConfirmSign } diff --git a/core/chain_indexer.go b/core/chain_indexer.go index b4c6745556..e8a4653d94 100644 --- a/core/chain_indexer.go +++ b/core/chain_indexer.go @@ -32,23 +32,19 @@ import ( "github.com/PlatONnetwork/PlatON-Go/log" ) -// 定义了处理区块链片段的方法,并把处理结果写入数据库 // ChainIndexerBackend defines the methods needed to process chain segments in // the background and write the segment results into the database. These can be // used to create filter blooms or CHTs. type ChainIndexerBackend interface { - // 用来初始化一个新的区块链片段,可能会终止任何没有完成的操作 // Reset initiates the processing of a new chain segment, potentially terminating // any partially completed operations (in case of a reorg). Reset(ctx context.Context, section uint64, prevHead common.Hash) error - // 对区块链片段中的下一个区块头进行处理。 调用者将确保区块头的连续顺序 // Process crunches through the next header in the chain segment. The caller // will ensure a sequential order of headers. Process(ctx context.Context, header *types.Header) error - // 完成区块链片段的元数据并将其存储到数据库中 // Commit finalizes the section metadata and stores it into the database. Commit() error } diff --git a/core/state/state_object.go b/core/state/state_object.go index ee78e38443..7f3afc5e3c 100644 --- a/core/state/state_object.go +++ b/core/state/state_object.go @@ -28,9 +28,6 @@ import ( "github.com/PlatONnetwork/PlatON-Go/rlp" ) -// account对象的抽象,提供了账户的一些功能。 -// 表示正在修改的以太坊账户 - var emptyCodeHash = crypto.Keccak256(nil) type Code []byte @@ -43,20 +40,17 @@ func (self Code) String() string { type Storage map[string]common.Hash type ValueStorage map[common.Hash][]byte -// 该结构:用于缓存智能合约中所有变量的值 // Storage -> hash : hash , common.Hash ([32]byte) //type Storage map[common.Hash]common.Hash func (self Storage) String() (str string) { for key, value := range self { - // %X -> 提供16进制 str += fmt.Sprintf("%X : %X\n", key, value) } return } -// 复制一份Storage func (self Storage) Copy() Storage { cpy := make(Storage) for key, value := range self { @@ -92,7 +86,6 @@ type stateObject struct { // unable to deal with database-level errors. Any error that occurs // during a database read is memoized here and will eventually be returned // by StateDB.Commit. - // 当一个对象被标记为自杀时,它将在状态转换的“更新”阶段期间从树中删除。 dbErr error // Write caches. @@ -100,7 +93,6 @@ type stateObject struct { // storage trie, which becomes non-nil on first access code Code // contract bytecode, which gets set when code is loaded - // todo: 新增,此字段尚不明确是否需要进行使用 abi Abi originStorage Storage // Storage cache of original entries to dedup rewrites @@ -124,13 +116,11 @@ func (s *stateObject) empty() bool { // Account is the Ethereum consensus representation of accounts. // These objects are stored in the main account trie. -// 帐户是以太坊共识表示的帐户。 这些对象存储在main account trie。 type Account struct { Nonce uint64 Balance *big.Int Root common.Hash // merkle root of the storage trie CodeHash []byte - // todo: 新增AbiHash字段 AbiHash []byte } @@ -287,7 +277,7 @@ func (self *stateObject) GetCommittedState(db Database, key string) []byte { func (self *stateObject) SetState(db Database, keyTrie string, valueKey common.Hash, value []byte) { //if the new value is the same as old,don't set - preValue := self.GetState(db, keyTrie) //获取value key + preValue := self.GetState(db, keyTrie) //get value key if bytes.Equal(preValue, value) { return } @@ -327,7 +317,6 @@ func (self *stateObject) updateTrie(db Database) Trie { delete(self.dirtyStorage, key) delete(self.dirtyValueStorage, valueKey) - //删除原来valueKey 对应的value delete(self.originValueStorage, self.originStorage[key]) self.originStorage[key] = valueKey @@ -499,9 +488,6 @@ func (self *stateObject) Value() *big.Int { panic("Value on stateObject should never be called") } -// todo: 新增方法 -// ======================================= 新增方法 =============================== - // todo: new method -> AbiHash func (self *stateObject) AbiHash() []byte { return self.data.AbiHash @@ -515,7 +501,6 @@ func (self *stateObject) Abi(db Database) []byte { if bytes.Equal(self.AbiHash(), emptyCodeHash) { return nil } - // 从树中提取code,入参:地址及hash, 此处需要深入发现获取规则 abi, err := db.ContractAbi(self.addrHash, common.BytesToHash(self.AbiHash())) if err != nil { self.setError(fmt.Errorf("can't load abi hash %x: %v", self.AbiHash(), err)) diff --git a/eth/downloader/downloader.go b/eth/downloader/downloader.go index eaf3056dc1..2d54fe4cb8 100644 --- a/eth/downloader/downloader.go +++ b/eth/downloader/downloader.go @@ -315,7 +315,7 @@ func (d *Downloader) UnregisterPeer(id string) error { // Synchronise tries to sync up our local block chain with a remote peer, both // adding various sanity checks as well as wrapping it with various log entries. func (d *Downloader) Synchronise(id string, head common.Hash, td *big.Int, mode SyncMode) error { - log.Warn("----------向对端节点同步区块数据----------", "peerID", id, "head", head, "td", td, "mode", mode) + log.Warn("~ Synchronize block data to the peer node", "peerID", id, "head", head, "td", td, "mode", mode) err := d.synchronise(id, head, td, mode) switch err { case nil: diff --git a/ethdb/database.go b/ethdb/database.go index 1848b5f5fa..33e9c3c89d 100644 --- a/ethdb/database.go +++ b/ethdb/database.go @@ -70,7 +70,7 @@ func NewLDBDatabase(file string, cache int, handles int) (*LDBDatabase, error) { } logger.Info("Allocated cache and file handles", "cache", cache, "handles", handles) - // 构建DB对象 + // Build DB instance. // Open the db and recover any potential corruptions db, err := leveldb.OpenFile(file, &opt.Options{ OpenFilesCacheCapacity: handles, diff --git a/event/feed.go b/event/feed.go index ffcf5fa950..f578f00c10 100644 --- a/event/feed.go +++ b/event/feed.go @@ -25,7 +25,7 @@ import ( var errBadChannel = errors.New("event: Subscribe argument does not have sendable channel type") // Feed implements one-to-many subscriptions where the carrier of events is a channel. -// Values sent to a Feed are delivered to all subscribed channels simultaneously.(同时的) +// Values sent to a Feed are delivered to all subscribed channels simultaneously. // // Feeds can only be used with a single type. The type is determined by the first Send or // Subscribe operation. Subsequent calls to these methods panic if the type does not diff --git a/miner/worker.go b/miner/worker.go index 9366184938..2f3c66f35b 100644 --- a/miner/worker.go +++ b/miner/worker.go @@ -164,8 +164,8 @@ type worker struct { taskCh chan *task resultCh chan *types.Block prepareResultCh chan *types.Block - blockSignatureCh chan *cbfttypes.BlockSignature // 签名 - cbftResultCh chan *cbfttypes.CbftResult // Seal出块后输出的channel + blockSignatureCh chan *cbfttypes.BlockSignature // signature + cbftResultCh chan *cbfttypes.CbftResult // Seal block and output to channel highestLogicalBlockCh chan *types.Block startCh chan struct{} exitCh chan struct{} @@ -410,7 +410,7 @@ func (w *worker) newWorkLoop(recommit time.Duration) { w.consensusCache.ClearCache(head.Block) case highestLogicalBlock := <-w.highestLogicalBlockCh: - log.Info("highestLogicalBlockCh通道接收数据", "number", highestLogicalBlock.NumberU64(), "hash", highestLogicalBlock.Hash()) + log.Info("highestLogicalBlockCh - Channel receiving data", "number", highestLogicalBlock.NumberU64(), "hash", highestLogicalBlock.Hash()) w.commitWorkEnv.highestLock.Lock() w.commitWorkEnv.highestLogicalBlock = highestLogicalBlock w.commitWorkEnv.highestLock.Unlock() @@ -418,7 +418,7 @@ func (w *worker) newWorkLoop(recommit time.Duration) { if w.isRunning() { if shouldSeal, error := w.engine.(consensus.Bft).ShouldSeal(); shouldSeal && error == nil { if shouldCommit, commitBlock := w.shouldCommit(time.Now().UnixNano() / 1e6); shouldCommit { - log.Warn("--------------highestLogicalBlock增长,并且间隔" + recommit.String() + "未执行打包任务,执行打包出块逻辑--------------") + log.Warn("~ HighestLogicalBlock increase, And interval " + recommit.String() + " Package task not executed,Execute packed out logic.") commit(false, commitInterruptResubmit, commitBlock) } } @@ -427,13 +427,12 @@ func (w *worker) newWorkLoop(recommit time.Duration) { case <-timer.C: // If mining is running resubmit a new work cycle periodically to pull in // higher priced transactions. Disable this overhead for pending blocks. - // timer控制,间隔recommit seconds进行出块,如果是cbft共识允许出空块 if w.isRunning() { - log.Warn("----------间隔" + recommit.String() + "开始打包任务----------") + log.Warn("~ Interval" + recommit.String() + " to start packing tasks.") if cbftEngine, ok := w.engine.(consensus.Bft); ok { if shouldSeal, error := cbftEngine.ShouldSeal(); shouldSeal && error == nil { if shouldCommit, commitBlock := w.shouldCommit(time.Now().UnixNano() / 1e6); shouldCommit { - log.Warn("--------------节点当前时间窗口出块,执行打包出块逻辑--------------") + log.Warn("~ The current time window of the node is out of the block, and the packaged block logic is executed.") commit(false, commitInterruptResubmit, commitBlock) continue } @@ -450,7 +449,7 @@ func (w *worker) newWorkLoop(recommit time.Duration) { } case interval := <-w.resubmitIntervalCh: - // cbft引擎不允许外界修改recommit值 + // cbft engine do not allow outside modifications recommit value. if _, ok := w.engine.(consensus.Bft); !ok { // Adjust resubmit interval explicitly by user. if interval < minRecommitInterval { @@ -466,7 +465,7 @@ func (w *worker) newWorkLoop(recommit time.Duration) { } case adjust := <-w.resubmitAdjustCh: - // cbft引擎不需要重新计算调整recommit值 + // cbft engine no need to recalculate adjustments recommit value. if _, ok := w.engine.(consensus.Bft); !ok { // Adjust resubmit interval by feedback. if adjust.inc { @@ -763,7 +762,7 @@ func (w *worker) resultLoop() { _receipts = task.receipts _state = task.state } else { - log.Info("从consensusCache中读取receipts、state", "blockHash", block.Hash(), "stateRoot", block.Root()) + log.Info("~ Read receipts、state from consensusCache", "blockHash", block.Hash(), "stateRoot", block.Root()) _receipts = w.consensusCache.ReadReceipts(block.Hash()) _state = w.consensusCache.ReadStateDB(block.Root()) } @@ -773,7 +772,7 @@ func (w *worker) resultLoop() { continue } - log.Warn("[2]共识成功", "blockNumber", block.NumberU64(), "timestamp", time.Now().UnixNano()/1e6) + log.Warn("[2]Consensus success", "blockNumber", block.NumberU64(), "timestamp", time.Now().UnixNano()/1e6) // Different block could share same sealhash, deep copy here to prevent write-write conflict. var ( @@ -937,7 +936,7 @@ func (w *worker) commitTransactions(txs *types.TransactionsByPriceAndNonce, coin for { if bftEngine && (float64(time.Now().UnixNano()/1e6-timestamp) >= w.commitDuration) { - log.Warn("------执行交易超时,主动退出,继续剩余打包流程------", "超时时长", w.commitDuration, "本轮执行交易数", w.current.tcount) + log.Warn("~ Execute transaction timeout, take the initiative to exit, continue the remaining packaging process", "Timeout period", w.commitDuration, "Number of executed transactions in the current round", w.current.tcount) break } // In the following three cases, we will interrupt the execution of the transaction. @@ -1082,7 +1081,7 @@ func (w *worker) commitNewWork(interrupt *int32, noempty bool, timestamp int64, header.Coinbase = w.coinbase } - log.Warn("[1]共识开始", "gasLimit", header.GasLimit, "blockNumber", header.Number, "timestamp", time.Now().UnixNano()/1e6) + log.Warn("[1]Consensus Start", "gasLimit", header.GasLimit, "blockNumber", header.Number, "timestamp", time.Now().UnixNano()/1e6) if err := w.engine.Prepare(w.chain, header); err != nil { log.Error("Failed to prepare header for mining", "err", err) return @@ -1215,7 +1214,7 @@ func (w *worker) commit(uncles []*types.Header, interval func(), update bool, st } select { case w.taskCh <- &task{receipts: receipts, state: s, block: block, createdAt: time.Now()}: - // 保存receipts、stateDB至缓存 + // save receipts、stateDB to cache. w.consensusCache.WriteReceipts(block.Hash(), receipts, block.NumberU64()) w.consensusCache.WriteStateDB(block.Root(), s, block.NumberU64()) diff --git a/params/protocol_params.go b/params/protocol_params.go index 36ee97e20c..f47febc30f 100644 --- a/params/protocol_params.go +++ b/params/protocol_params.go @@ -29,7 +29,7 @@ const ( CallValueTransferGas uint64 = 9000 // Paid for CALL when the value transfer is non-zero. CallNewAccountGas uint64 = 25000 // Paid for CALL when the destination address didn't exist prior. TxGas uint64 = 21000 // Per transaction not creating a contract. NOTE: Not payable on data of calls between transactions. - // todo: 而已创建gas需要的值,此处需要处理 pre value: 53000 + // todo: pre value: 53000 TxGasContractCreation uint64 = 453000 // Per transaction that creates a contract. NOTE: Not payable on data of calls between transactions. TxDataZeroGas uint64 = 4 // Per byte of data attached to a transaction that equals zero. NOTE: Not payable on data of calls between transactions. QuadCoeffDiv uint64 = 512 // Divisor for the quadratic particle of the memory cost equation. diff --git a/rlp/encode_test.go b/rlp/encode_test.go index 5b1d73f938..565290832b 100644 --- a/rlp/encode_test.go +++ b/rlp/encode_test.go @@ -291,10 +291,10 @@ func TestEncodeF03(t *testing.T) { fmt.Println(string(res)) //val := []interface{}{"transfer", uint(0xFFFFFF), []interface{}{[]uint{4, 5, 5}}, "abc"} - fmt.Println([]byte("人才是你吗")) + fmt.Println([]byte("Hello")) var source [][]byte source = make([][]byte, 0) - source = append(source, []byte("人才是你吗")) + source = append(source, []byte("Hello")) source = append(source, uint64ToBytes(1000)) source = append(source, uint64ToBytes(2000)) source = append(source, boolToBytes(false)) @@ -306,7 +306,7 @@ func TestEncodeF03(t *testing.T) { fmt.Println(err) t.Errorf("fail") } - // 编码后字节数组 + encodedBytes := buffer.Bytes() fmt.Println(encodedBytes) @@ -317,7 +317,7 @@ func TestEncodeF03(t *testing.T) { fmt.Println(deref) for i, v := range deref.([]interface{}) { // fmt.Println(i," ",hex.EncodeToString(v.([]byte))) - // 类型判断,然后转换 + // Type judgment, then convert switch i { case 0: fmt.Println(string(v.([]byte))) diff --git a/tests/study/training_lesson.go b/tests/study/training_lesson.go deleted file mode 100644 index 4a31cbd354..0000000000 --- a/tests/study/training_lesson.go +++ /dev/null @@ -1,103 +0,0 @@ -package main - -import ( - "fmt" - "net/http" - "os" - "time" -) - -//定义struct,作为http的handler -type MessageHandler struct { - //处理get/post数据的channel - ch chan string -} - -//MessageHandler需要实现ServeHTTP方法,才能正式成为一个handler -func (m *MessageHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { - r.ParseForm() - if len(r.FormValue("message")) > 0 { - fmt.Println("message:", r.FormValue("message")) - fmt.Fprintf(w, r.FormValue("message")) - m.ch <- r.FormValue("message") - } -} - -//启动http server -func startHttpServer(ch chan string, f *os.File) { - //初始化MessageHandler,并注册到http中 - http.Handle("/test", &MessageHandler{ch}) - err := http.ListenAndServe(":8080", nil) - if err != nil { - fmt.Println("http server start error!", err) - return - } -} - -//写文件的loop -func fileWriterLoop(ch chan string, f *os.File) { - - //声明并初始化一个capacity=2的slice - msgBuffer := make([]string, 0, 2) - for { - //从ch中读取数据,并附上换行符,放入slice - msgBuffer = append(msgBuffer, <-ch+"\r\n") - if len(msgBuffer) == 2 { //slice长度==2,则写文件 - for _, msg := range msgBuffer { - //把slice中的字符串,一个个写入文件 - _, err := f.WriteString(msg) - if err != nil { - fmt.Println("write message to file error:", err) - } - } - //重置slice,内容清空,长度设置为0 - msgBuffer = msgBuffer[0:0] - } - } -} - -func main3() { - //声明并初始化一个带buffer的channel - ch := make(chan string, 99) - f, err := os.OpenFile("d:\\test.txt", os.O_RDWR|os.O_CREATE, 0766) - if err != nil { - fmt.Println("open file failed") - return - } - defer f.Close() - - //1st. start fileWriter goroutine - go fileWriterLoop(ch, f) - - //2nd. start receiver goroutine - go startHttpServer(ch, f) - - //waiting.... - time.Sleep(time.Duration(10000) * time.Second) - -} - -func main() { - ch := make(chan int) - param := 3 - var param1 int - go func() { - select { - case param1 = <-ch: - fmt.Printf("received %d from ch\n", param1) - //default: - //fmt.Printf("no communication222\n") - } - }() - - go func() { - select { - case ch <- param: - fmt.Printf("sent %d to ch\n", param) - default: - fmt.Println("no communication111") - } - }() - - time.Sleep(time.Duration(2000)) -} diff --git a/tests/study/training_lesson_test.go b/tests/study/training_lesson_test.go deleted file mode 100644 index 9bc869b860..0000000000 --- a/tests/study/training_lesson_test.go +++ /dev/null @@ -1,39 +0,0 @@ -package main - -import ( - "fmt" - "io/ioutil" - "net/http" - "testing" -) - -const ( - message = "shanghai" -) - -var dataList = []string{"test1", "test2", "test3", "test4", "test5", "test6", "test7", "test8", "test9", "test10"} - -func TestSendMessage(t *testing.T) { - - for _, data := range dataList { - t.Run(fmt.Sprintf("send:%s", data), func(t *testing.T) { - - resp, err := http.Get("http://localhost:8080/test?message=" + data) - - if err != nil { - // handle error - } - defer resp.Body.Close() - - body, err := ioutil.ReadAll(resp.Body) - if err != nil { - // handle error - } - fmt.Println(string(body)) - // 检测返回的数据 - if string(body) != data { - t.Errorf("handler returned unexpected body: got %v want %v", string(body), data) - } - }) - } -} diff --git a/trie/encoding.go b/trie/encoding.go index 1940cef483..f0becb3efa 100644 --- a/trie/encoding.go +++ b/trie/encoding.go @@ -35,7 +35,7 @@ package trie // into the remaining bytes. Compact encoding is used for nodes stored on disk. func hexToCompact(hex []byte) []byte { - terminator := byte(0) // 分隔符 + terminator := byte(0) // Separator if hasTerm(hex) { terminator = 1 hex = hex[:len(hex)-1]