2017-12-24

This commit is contained in:
qgzhao197504050036 2017-12-24 11:07:14 +08:00
parent 732f5468d3
commit b44e7d10e3
65 changed files with 338 additions and 215 deletions

View file

@ -385,7 +385,7 @@ func (w *wallet) selfDerive() {
// Display a log message to the user for new (or previously empty accounts) // Display a log message to the user for new (or previously empty accounts)
if _, known := w.paths[nextAddr]; !known || (!empty && nextAddr == w.deriveNextAddr) { if _, known := w.paths[nextAddr]; !known || (!empty && nextAddr == w.deriveNextAddr) {
w.log.Info("USB wallet discovered new account", "address", nextAddr, "path", path, "balance", balance, "nonce", nonce) w.log.Info("USB钱包发现新帐号", "地址", nextAddr, "路径", path, "帐户", balance, "随机数", nonce)
} }
// Fetch the next potential account // Fetch the next potential account
if !empty { if !empty {

View file

@ -215,11 +215,11 @@ func unlockAccount(ctx *cli.Context, ks *keystore.KeyStore, address string, i in
password := getPassPhrase(prompt, false, i, passwords) password := getPassPhrase(prompt, false, i, passwords)
err = ks.Unlock(account, password) err = ks.Unlock(account, password)
if err == nil { if err == nil {
log.Info("Unlocked account", "address", account.Address.Hex()) log.Info("解锁帐号", "地址", account.Address.Hex())
return account, password return account, password
} }
if err, ok := err.(*keystore.AmbiguousAddrError); ok { if err, ok := err.(*keystore.AmbiguousAddrError); ok {
log.Info("Unlocked account", "address", account.Address.Hex()) log.Info("解锁帐号", "地址", account.Address.Hex())
return ambiguousAddrRecovery(ks, err, password), password return ambiguousAddrRecovery(ks, err, password), password
} }
if err != keystore.ErrDecrypt { if err != keystore.ErrDecrypt {

View file

@ -169,7 +169,7 @@ func initGenesis(ctx *cli.Context) error {
if err != nil { if err != nil {
utils.Fatalf("Failed to write genesis block: %v", err) utils.Fatalf("Failed to write genesis block: %v", err)
} }
log.Info("Successfully wrote genesis state", "database", name, "hash", hash) log.Info("创始块状态创建成功", "database", name, "hash", hash)
} }
return nil return nil
} }
@ -207,7 +207,7 @@ func importChain(ctx *cli.Context) error {
} else { } else {
for _, arg := range ctx.Args() { for _, arg := range ctx.Args() {
if err := utils.ImportChain(chain, arg); err != nil { if err := utils.ImportChain(chain, arg); err != nil {
log.Error("Import error", "file", arg, "err", err) log.Error("导入错误", "文件", arg, "err", err)
} }
} }
} }

BIN
cmd/geth/geth.exe Normal file

Binary file not shown.

View file

@ -261,7 +261,7 @@ func startNode(ctx *cli.Context, stack *node.Node) {
} }
case accounts.WalletOpened: case accounts.WalletOpened:
status, _ := event.Wallet.Status() status, _ := event.Wallet.Status()
log.Info("New wallet appeared", "url", event.Wallet.URL(), "status", status) log.Info("出现新钱包", "url", event.Wallet.URL(), "状态", status)
if event.Wallet.URL().Scheme == "ledger" { if event.Wallet.URL().Scheme == "ledger" {
event.Wallet.SelfDerive(accounts.DefaultLedgerBaseDerivationPath, stateReader) event.Wallet.SelfDerive(accounts.DefaultLedgerBaseDerivationPath, stateReader)
@ -270,7 +270,7 @@ func startNode(ctx *cli.Context, stack *node.Node) {
} }
case accounts.WalletDropped: case accounts.WalletDropped:
log.Info("Old wallet dropped", "url", event.Wallet.URL()) log.Info("旧钱包被删除", "url", event.Wallet.URL())
event.Wallet.Close() event.Wallet.Close()
} }
} }

View file

@ -56,7 +56,7 @@ services:
// HTTP services running on a single host. If an instance with the specified // HTTP services running on a single host. If an instance with the specified
// network name already exists there, it will be overwritten! // network name already exists there, it will be overwritten!
func deployNginx(client *sshClient, network string, port int, nocache bool) ([]byte, error) { func deployNginx(client *sshClient, network string, port int, nocache bool) ([]byte, error) {
log.Info("Deploying nginx reverse-proxy", "server", client.server, "port", port) log.Info("使用nginx解析代理", "服务器", client.server, "端口", port)
// Generate the content to upload to the server // Generate the content to upload to the server
workdir := fmt.Sprintf("%d", rand.Int63()) workdir := fmt.Sprintf("%d", rand.Int63())

View file

@ -202,7 +202,7 @@ func (info *nodeInfos) Report() map[string]string {
if err := json.Unmarshal([]byte(info.keyJSON), &key); err == nil { if err := json.Unmarshal([]byte(info.keyJSON), &key); err == nil {
report["Signer account"] = common.HexToAddress(key.Address).Hex() report["Signer account"] = common.HexToAddress(key.Address).Hex()
} else { } else {
log.Error("Failed to retrieve signer address", "err", err) log.Error("检索签名地址失败", "错误", err)
} }
} }
} }

View file

@ -110,7 +110,7 @@ func (w *wizard) deployExplorer() {
return return
} }
// All ok, run a network scan to pick any changes up // All ok, run a network scan to pick any changes up
log.Info("Waiting for node to finish booting") log.Info("等待节点完成启动")
time.Sleep(3 * time.Second) time.Sleep(3 * time.Second)
w.networkStats() w.networkStats()

View file

@ -124,7 +124,7 @@ func (w *wizard) makeGenesis() {
genesis.Config.ChainId = new(big.Int).SetUint64(uint64(w.readDefaultInt(rand.Intn(65536)))) genesis.Config.ChainId = new(big.Int).SetUint64(uint64(w.readDefaultInt(rand.Intn(65536))))
// All done, store the genesis and flush to disk // All done, store the genesis and flush to disk
log.Info("Configured new genesis block") log.Info("配置新的创世区块")
w.conf.Genesis = genesis w.conf.Genesis = genesis
w.conf.flush() w.conf.flush()
@ -174,7 +174,7 @@ func (w *wizard) manageGenesis() {
if err := ioutil.WriteFile(w.readDefaultString(fmt.Sprintf("%s.json", w.network)), out, 0644); err != nil { if err := ioutil.WriteFile(w.readDefaultString(fmt.Sprintf("%s.json", w.network)), out, 0644); err != nil {
log.Error("Failed to save genesis file", "err", err) log.Error("Failed to save genesis file", "err", err)
} }
log.Info("Exported existing genesis block") log.Info("导出已存在的创世区块")
case choice == "3": case choice == "3":
// Make sure we don't have any services running // Make sure we don't have any services running
@ -182,12 +182,12 @@ func (w *wizard) manageGenesis() {
log.Error("Genesis reset requires all services and servers torn down") log.Error("Genesis reset requires all services and servers torn down")
return return
} }
log.Info("Genesis block destroyed") log.Info("创世区块被破坏")
w.conf.Genesis = nil w.conf.Genesis = nil
w.conf.flush() w.conf.flush()
default: default:
log.Error("That's not something I can do") log.Error("已超出能力范围")
} }
} }

View file

@ -70,7 +70,7 @@ func (w *wizard) run() {
log.Error("I also like to live dangerously, still no spaces") log.Error("I also like to live dangerously, still no spaces")
} }
} }
log.Info("Administering Ethereum network", "name", w.network) log.Info("管理消品网络", "名字", w.network)
// Load initial configurations and connect to all live servers // Load initial configurations and connect to all live servers
w.conf.path = filepath.Join(os.Getenv("HOME"), ".puppeth", w.network) w.conf.path = filepath.Join(os.Getenv("HOME"), ".puppeth", w.network)
@ -89,10 +89,10 @@ func (w *wizard) run() {
go func(server string, pubkey []byte) { go func(server string, pubkey []byte) {
defer pend.Done() defer pend.Done()
log.Info("Dialing previously configured server", "server", server) log.Info("接入以前所配置的服务器", "服务器", server)
client, err := dial(server, pubkey) client, err := dial(server, pubkey)
if err != nil { if err != nil {
log.Error("Previous server unreachable", "server", server, "err", err) log.Error("以前的服务器不可接入", "服务器", server, "错误", err)
} }
w.lock.Lock() w.lock.Lock()
w.servers[server] = client w.servers[server] = client

View file

@ -32,7 +32,7 @@ import (
// configuration set to give users hints on how to do various tasks. // configuration set to give users hints on how to do various tasks.
func (w *wizard) networkStats() { func (w *wizard) networkStats() {
if len(w.servers) == 0 { if len(w.servers) == 0 {
log.Info("No remote machines to gather stats from") log.Info("没有远程设备收集统计数据")
return return
} }
// Clear out some previous configs to refill from current scan // Clear out some previous configs to refill from current scan

View file

@ -52,7 +52,7 @@ func (w *wizard) manageServers() {
delete(w.conf.Servers, server) delete(w.conf.Servers, server)
w.conf.flush() w.conf.flush()
log.Info("Disconnected existing server", "server", server) log.Info("断开现有服务器", "服务器", server)
w.networkStats() w.networkStats()
return return
} }
@ -158,7 +158,7 @@ func (w *wizard) manageComponents() {
} }
} }
} }
log.Info("Torn down existing component", "server", server, "service", service) log.Info("停止现存组件", "服务器", server, "服务", service)
return return
} }
// If the user requested deploying a new component, do it // If the user requested deploying a new component, do it

View file

@ -171,7 +171,7 @@ func (w *wizard) deployNode(boot bool) {
return return
} }
// All ok, run a network scan to pick any changes up // All ok, run a network scan to pick any changes up
log.Info("Waiting for node to finish booting") log.Info("等待节点完成启动")
time.Sleep(3 * time.Second) time.Sleep(3 * time.Second)
w.networkStats() w.networkStats()

View file

@ -106,7 +106,7 @@ func (w *wizard) deployWallet() {
return return
} }
// All ok, run a network scan to pick any changes up // All ok, run a network scan to pick any changes up
log.Info("Waiting for node to finish booting") log.Info("等待节点完成启动")
time.Sleep(3 * time.Second) time.Sleep(3 * time.Second)
w.networkStats() w.networkStats()

View file

@ -57,7 +57,7 @@ func dbExport(ctx *cli.Context) {
utils.Fatalf("error exporting local chunk database: %s", err) utils.Fatalf("error exporting local chunk database: %s", err)
} }
log.Info(fmt.Sprintf("successfully exported %d chunks", count)) log.Info(fmt.Sprintf("成功导出 %d 区块", count))
} }
func dbImport(ctx *cli.Context) { func dbImport(ctx *cli.Context) {
@ -89,7 +89,7 @@ func dbImport(ctx *cli.Context) {
utils.Fatalf("error importing local chunk database: %s", err) utils.Fatalf("error importing local chunk database: %s", err)
} }
log.Info(fmt.Sprintf("successfully imported %d chunks", count)) log.Info(fmt.Sprintf("成功导放 %d 区块", count))
} }
func dbClean(ctx *cli.Context) { func dbClean(ctx *cli.Context) {

View file

@ -397,7 +397,7 @@ func bzzd(ctx *cli.Context) error {
signal.Notify(sigc, syscall.SIGTERM) signal.Notify(sigc, syscall.SIGTERM)
defer signal.Stop(sigc) defer signal.Stop(sigc)
<-sigc <-sigc
log.Info("Got sigterm, shutting swarm down...") log.Info("获得签名条目, swarm下线...")
stack.Stop() stack.Stop()
}() }()
@ -436,11 +436,11 @@ func detectEnsAddr(client *rpc.Client) (common.Address, error) {
switch { switch {
case version == "1" && block.Hash() == params.MainnetGenesisHash: case version == "1" && block.Hash() == params.MainnetGenesisHash:
log.Info("using Mainnet ENS contract address", "addr", ens.MainNetAddress) log.Info("使用主网络ENS合约地址", "地址", ens.MainNetAddress)
return ens.MainNetAddress, nil return ens.MainNetAddress, nil
case version == "3" && block.Hash() == params.TestnetGenesisHash: case version == "3" && block.Hash() == params.TestnetGenesisHash:
log.Info("using Testnet ENS contract address", "addr", ens.TestNetAddress) log.Info("使用测试网ENS合约地址", "地址", ens.TestNetAddress)
return ens.TestNetAddress, nil return ens.TestNetAddress, nil
default: default:
@ -484,19 +484,19 @@ func registerBzzService(ctx *cli.Context, stack *node.Node) {
boot := func(ctx *node.ServiceContext) (node.Service, error) { boot := func(ctx *node.ServiceContext) (node.Service, error) {
var swapClient *ethclient.Client var swapClient *ethclient.Client
if swapapi != "" { if swapapi != "" {
log.Info("connecting to SWAP API", "url", swapapi) log.Info("连接到SWAP API", "url", swapapi)
swapClient, err = ethclient.Dial(swapapi) swapClient, err = ethclient.Dial(swapapi)
if err != nil { if err != nil {
return nil, fmt.Errorf("error connecting to SWAP API %s: %s", swapapi, err) return nil, fmt.Errorf("错误连入SWAP API %s: %s", swapapi, err)
} }
} }
var ensClient *ethclient.Client var ensClient *ethclient.Client
if ensapi != "" { if ensapi != "" {
log.Info("connecting to ENS API", "url", ensapi) log.Info("连入ENS API", "url", ensapi)
client, err := rpc.Dial(ensapi) client, err := rpc.Dial(ensapi)
if err != nil { if err != nil {
return nil, fmt.Errorf("error connecting to ENS API %s: %s", ensapi, err) return nil, fmt.Errorf("错误连入ENS API %s: %s", ensapi, err)
} }
ensClient = ethclient.NewClient(client) ensClient = ethclient.NewClient(client)
@ -507,7 +507,7 @@ func registerBzzService(ctx *cli.Context, stack *node.Node) {
if err == nil { if err == nil {
bzzconfig.EnsRoot = ensAddr bzzconfig.EnsRoot = ensAddr
} else { } else {
log.Warn(fmt.Sprintf("could not determine ENS contract address, using default %s", bzzconfig.EnsRoot), "err", err) log.Warn(fmt.Sprintf("不同决定ENS合约地址, 使用缺省 %s", bzzconfig.EnsRoot), "err", err)
} }
} }
} }
@ -527,7 +527,7 @@ func getAccount(ctx *cli.Context, stack *node.Node) *ecdsa.PrivateKey {
} }
// Try to load the arg as a hex key file. // Try to load the arg as a hex key file.
if key, err := crypto.LoadECDSA(keyid); err == nil { if key, err := crypto.LoadECDSA(keyid); err == nil {
log.Info("Swarm account key loaded", "address", crypto.PubkeyToAddress(key.PublicKey)) log.Info("Swarm 帐号密钥加载", "地址", crypto.PubkeyToAddress(key.PublicKey))
return key return key
} }
// Otherwise try getting it from the keystore. // Otherwise try getting it from the keystore.
@ -546,7 +546,7 @@ func decryptStoreAccount(ks *keystore.KeyStore, account string, passwords []stri
if accounts := ks.Accounts(); len(accounts) > ix { if accounts := ks.Accounts(); len(accounts) > ix {
a = accounts[ix] a = accounts[ix]
} else { } else {
err = fmt.Errorf("index %d higher than number of accounts %d", ix, len(accounts)) err = fmt.Errorf("索引 %d 超出帐号数量 %d", ix, len(accounts))
} }
} else { } else {
utils.Fatalf("Can't find swarm account key %s", account) utils.Fatalf("Can't find swarm account key %s", account)

View file

@ -67,12 +67,12 @@ func StartNode(stack *node.Node) {
signal.Notify(sigc, os.Interrupt) signal.Notify(sigc, os.Interrupt)
defer signal.Stop(sigc) defer signal.Stop(sigc)
<-sigc <-sigc
log.Info("Got interrupt, shutting down...") log.Info("收到中断指令,准备下线...")
go stack.Stop() go stack.Stop()
for i := 10; i > 0; i-- { for i := 10; i > 0; i-- {
<-sigc <-sigc
if i > 1 { if i > 1 {
log.Warn("Already shutting down, interrupt more to panic.", "times", i-1) log.Warn("已经下线, 无需再发中断指令.", "次数", i-1)
} }
} }
debug.Exit() // ensure trace and CPU profile data is flushed. debug.Exit() // ensure trace and CPU profile data is flushed.
@ -90,7 +90,7 @@ func ImportChain(chain *core.BlockChain, fn string) error {
defer close(interrupt) defer close(interrupt)
go func() { go func() {
if _, ok := <-interrupt; ok { if _, ok := <-interrupt; ok {
log.Info("Interrupted during import, stopping at next batch") log.Info("导入期间中断, 在下一个批次停止")
} }
close(stop) close(stop)
}() }()
@ -103,7 +103,7 @@ func ImportChain(chain *core.BlockChain, fn string) error {
} }
} }
log.Info("Importing blockchain", "file", fn) log.Info("导入区块链", "文件", fn)
fh, err := os.Open(fn) fh, err := os.Open(fn)
if err != nil { if err != nil {
return err return err
@ -151,7 +151,7 @@ func ImportChain(chain *core.BlockChain, fn string) error {
return fmt.Errorf("interrupted") return fmt.Errorf("interrupted")
} }
if hasAllBlocks(chain, blocks[:i]) { if hasAllBlocks(chain, blocks[:i]) {
log.Info("Skipping batch as all blocks present", "batch", batch, "first", blocks[0].Hash(), "last", blocks[i-1].Hash()) log.Info("所有区块存在,跳过批处理", "批处理", batch, "第一个", blocks[0].Hash(), "最后一个", blocks[i-1].Hash())
continue continue
} }
@ -172,7 +172,7 @@ func hasAllBlocks(chain *core.BlockChain, bs []*types.Block) bool {
} }
func ExportChain(blockchain *core.BlockChain, fn string) error { func ExportChain(blockchain *core.BlockChain, fn string) error {
log.Info("Exporting blockchain", "file", fn) log.Info("导出区块链", "文件", fn)
fh, err := os.OpenFile(fn, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, os.ModePerm) fh, err := os.OpenFile(fn, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, os.ModePerm)
if err != nil { if err != nil {
return err return err
@ -188,13 +188,13 @@ func ExportChain(blockchain *core.BlockChain, fn string) error {
if err := blockchain.Export(writer); err != nil { if err := blockchain.Export(writer); err != nil {
return err return err
} }
log.Info("Exported blockchain", "file", fn) log.Info("导出区块链", "文件", fn)
return nil return nil
} }
func ExportAppendChain(blockchain *core.BlockChain, fn string, first uint64, last uint64) error { func ExportAppendChain(blockchain *core.BlockChain, fn string, first uint64, last uint64) error {
log.Info("Exporting blockchain", "file", fn) log.Info("正在导出区块链", "文件", fn)
// TODO verify mode perms // TODO verify mode perms
fh, err := os.OpenFile(fn, os.O_CREATE|os.O_APPEND|os.O_WRONLY, os.ModePerm) fh, err := os.OpenFile(fn, os.O_CREATE|os.O_APPEND|os.O_WRONLY, os.ModePerm)
if err != nil { if err != nil {
@ -211,6 +211,6 @@ func ExportAppendChain(blockchain *core.BlockChain, fn string, first uint64, las
if err := blockchain.ExportN(writer, first, last); err != nil { if err := blockchain.ExportN(writer, first, last); err != nil {
return err return err
} }
log.Info("Exported blockchain to", "file", fn) log.Info("导出区块链到", "文件", fn)
return nil return nil
} }

View file

@ -1059,7 +1059,7 @@ func SetEthConfig(ctx *cli.Context, stack *node.Node, cfg *eth.Config) {
if err := ks.Unlock(developer, ""); err != nil { if err := ks.Unlock(developer, ""); err != nil {
Fatalf("Failed to unlock developer account: %v", err) Fatalf("Failed to unlock developer account: %v", err)
} }
log.Info("Using developer account", "address", developer.Address) log.Info("使用开发者帐户", "地址", developer.Address)
cfg.Genesis = core.DeveloperGenesisBlock(uint64(ctx.GlobalInt(DeveloperPeriodFlag.Name)), developer.Address) cfg.Genesis = core.DeveloperGenesisBlock(uint64(ctx.GlobalInt(DeveloperPeriodFlag.Name)), developer.Address)
if !ctx.GlobalIsSet(GasPriceFlag.Name) { if !ctx.GlobalIsSet(GasPriceFlag.Name) {

View file

@ -623,7 +623,7 @@ func (c *Clique) Seal(chain consensus.ChainReader, block *types.Block, stop <-ch
if recent == signer { if recent == signer {
// Signer is among recents, only wait if the current block doesn't shift it out // Signer is among recents, only wait if the current block doesn't shift it out
if limit := uint64(len(snap.Signers)/2 + 1); number < limit || seen > number-limit { if limit := uint64(len(snap.Signers)/2 + 1); number < limit || seen > number-limit {
log.Info("Signed recently, must wait for others") log.Info("最新签名, 必须等待其他人")
<-stop <-stop
return nil, nil return nil, nil
} }

View file

@ -94,7 +94,7 @@ func generateCache(dest []uint32, epoch uint64, seed []byte) {
if elapsed > 3*time.Second { if elapsed > 3*time.Second {
logFn = logger.Info logFn = logger.Info
} }
logFn("Generated ethash verification cache", "elapsed", common.PrettyDuration(elapsed)) logFn("生成ethash验证缓存", "耗时", common.PrettyDuration(elapsed))
}() }()
// Convert our destination slice to a byte buffer // Convert our destination slice to a byte buffer
header := *(*reflect.SliceHeader)(unsafe.Pointer(&dest)) header := *(*reflect.SliceHeader)(unsafe.Pointer(&dest))
@ -231,7 +231,7 @@ func generateDataset(dest []uint32, epoch uint64, cache []uint32) {
if elapsed > 3*time.Second { if elapsed > 3*time.Second {
logFn = logger.Info logFn = logger.Info
} }
logFn("Generated ethash verification cache", "elapsed", common.PrettyDuration(elapsed)) logFn("生成ethash验证缓存", "耗时", common.PrettyDuration(elapsed))
}() }()
// Figure out whether the bytes need to be swapped for the machine // Figure out whether the bytes need to be swapped for the machine
@ -275,7 +275,7 @@ func generateDataset(dest []uint32, epoch uint64, cache []uint32) {
copy(dataset[index*hashBytes:], item) copy(dataset[index*hashBytes:], item)
if status := atomic.AddUint32(&progress, 1); status%percent == 0 { if status := atomic.AddUint32(&progress, 1); status%percent == 0 {
logger.Info("Generating DAG in progress", "percentage", uint64(status*100)/(size/hashBytes), "elapsed", common.PrettyDuration(time.Since(start))) logger.Info("DAG文件生成进度", "百分比", uint64(status*100)/(size/hashBytes), "耗时", common.PrettyDuration(time.Since(start)))
} }
} }
}(i) }(i)

View file

@ -36,8 +36,12 @@ import (
// Ethash proof-of-work protocol constants. // Ethash proof-of-work protocol constants.
var ( var (
FrontierBlockReward *big.Int = big.NewInt(5e+18) // Block reward in wei for successfully mining a block //BlockReward *big.Int = big.NewInt(4e+18) // Block reward in wei for successfully mining a block
ByzantiumBlockReward *big.Int = big.NewInt(3e+18) // Block reward in wei for successfully mining a block upward from Byzantium //lockReward *big.Int = big.NewInt(2e+18) // Block reward in wei for successfully mining a block upward from Byzantium
blockReward *big.Int = big.NewInt(18e17) // Block reward in wei for successfully mining a block
XF_reward *big.Int = big.NewInt(9e17)
KY_reward *big.Int = big.NewInt(3e17) // Block reward in wei for successfully mining a block
//KY_blockReward *big.Int = big.NewInt(1e0)
maxUncles = 2 // Maximum number of uncles allowed in a single block maxUncles = 2 // Maximum number of uncles allowed in a single block
) )
@ -292,8 +296,8 @@ func CalcDifficulty(config *params.ChainConfig, time uint64, parent *types.Heade
switch { switch {
case config.IsByzantium(next): case config.IsByzantium(next):
return calcDifficultyByzantium(time, parent) return calcDifficultyByzantium(time, parent)
case config.IsHomestead(next): //case config.IsHomestead(next):
return calcDifficultyHomestead(time, parent) // return calcDifficultyHomestead(time, parent)
default: default:
return calcDifficultyFrontier(time, parent) return calcDifficultyFrontier(time, parent)
} }
@ -407,7 +411,6 @@ func calcDifficultyHomestead(time uint64, parent *types.Header) *big.Int {
// for the exponential factor // for the exponential factor
periodCount := new(big.Int).Add(parent.Number, big1) periodCount := new(big.Int).Add(parent.Number, big1)
periodCount.Div(periodCount, expDiffPeriod) periodCount.Div(periodCount, expDiffPeriod)
// the exponential factor, commonly referred to as "the bomb" // the exponential factor, commonly referred to as "the bomb"
// diff = diff + 2^(periodCount - 2) // diff = diff + 2^(periodCount - 2)
if periodCount.Cmp(big1) > 0 { if periodCount.Cmp(big1) > 0 {
@ -415,6 +418,7 @@ func calcDifficultyHomestead(time uint64, parent *types.Header) *big.Int {
y.Exp(big2, y, nil) y.Exp(big2, y, nil)
x.Add(x, y) x.Add(x, y)
} }
return x return x
} }
@ -431,6 +435,7 @@ func calcDifficultyFrontier(time uint64, parent *types.Header) *big.Int {
bigParentTime.Set(parent.Time) bigParentTime.Set(parent.Time)
if bigTime.Sub(bigTime, bigParentTime).Cmp(params.DurationLimit) < 0 { if bigTime.Sub(bigTime, bigParentTime).Cmp(params.DurationLimit) < 0 {
//log.Info("挖矿参数", "bigTime", bigTime, "bigParentTime", bigParentTime, "Adjust", adjust)
diff.Add(parent.Difficulty, adjust) diff.Add(parent.Difficulty, adjust)
} else { } else {
diff.Sub(parent.Difficulty, adjust) diff.Sub(parent.Difficulty, adjust)
@ -455,6 +460,7 @@ func calcDifficultyFrontier(time uint64, parent *types.Header) *big.Int {
// the PoW difficulty requirements. // the PoW difficulty requirements.
func (ethash *Ethash) VerifySeal(chain consensus.ChainReader, header *types.Header) error { func (ethash *Ethash) VerifySeal(chain consensus.ChainReader, header *types.Header) error {
// If we're running a fake PoW, accept any seal as valid // If we're running a fake PoW, accept any seal as valid
var diff_just *big.Int
if ethash.config.PowMode == ModeFake || ethash.config.PowMode == ModeFullFake { if ethash.config.PowMode == ModeFake || ethash.config.PowMode == ModeFullFake {
time.Sleep(ethash.fakeDelay) time.Sleep(ethash.fakeDelay)
if ethash.fakeFail == header.Number.Uint64() { if ethash.fakeFail == header.Number.Uint64() {
@ -487,10 +493,26 @@ func (ethash *Ethash) VerifySeal(chain consensus.ChainReader, header *types.Head
if !bytes.Equal(header.MixDigest[:], digest) { if !bytes.Equal(header.MixDigest[:], digest) {
return errInvalidMixDigest return errInvalidMixDigest
} }
target := new(big.Int).Div(maxUint256, header.Difficulty)
var just_time *big.Int
if header.Tokentime.Cmp(big.NewInt(1)) < 0 {
just_time = big.NewInt(1)
} else {
just_time = header.Tokentime
}
if just_time.Cmp(header.Difficulty) > 0 {
diff_just = big.NewInt(1)
} else {
diff_just = new(big.Int).Div(header.Difficulty, just_time)
}
//diff_just = new(big.Int).Div(header.Difficulty, just_time)
//target = new(big.Int).Div(maxUint256, header.Difficulty)
target := new(big.Int).Div(maxUint256, diff_just)
//target := new(big.Int).Div(maxUint256, header.Difficulty)
if new(big.Int).SetBytes(result).Cmp(target) > 0 { if new(big.Int).SetBytes(result).Cmp(target) > 0 {
return errInvalidPoW return errInvalidPoW
} }
//log.Info("消品链验证","区块号",header.Number, "消品权重",header.Tokentime,"封装难度",header.Difficulty)
return nil return nil
} }
@ -529,12 +551,29 @@ var (
// TODO (karalabe): Move the chain maker into this package and make this private! // TODO (karalabe): Move the chain maker into this package and make this private!
func AccumulateRewards(config *params.ChainConfig, state *state.StateDB, header *types.Header, uncles []*types.Header) { func AccumulateRewards(config *params.ChainConfig, state *state.StateDB, header *types.Header, uncles []*types.Header) {
// Select the correct block reward based on chain progression // Select the correct block reward based on chain progression
blockReward := FrontierBlockReward //blockReward := FrontierBlockReward
if config.IsByzantium(header.Number) { //if config.IsByzantium(header.Number) {
blockReward = ByzantiumBlockReward // blockReward = ByzantiumBlockReward
} //}
// Accumulate the rewards for the miner and any included uncles // Accumulate the rewards for the miner and any included uncles
//reward := new(big.Int).Set(blockReward)
//r := new(big.Int)
//for _, uncle := range uncles {
// r.Add(uncle.Number, big8)
// r.Sub(r, header.Number)
// r.Mul(r, blockReward)
// r.Div(r, big8)
// state.AddBalance(uncle.Coinbase, r)
// r.Div(blockReward, big32)
// reward.Add(reward, r)
//}
//state.AddBalance(header.Coinbase, reward)
reward := new(big.Int).Set(blockReward) reward := new(big.Int).Set(blockReward)
//var XP_GD = common.HexToAddress("0xf933b0CF38a270938B9D6bb41f004374363C3EC0")
var XP_XF = params.XP_XF
var XP_KY = params.XP_KY
r := new(big.Int) r := new(big.Int)
for _, uncle := range uncles { for _, uncle := range uncles {
r.Add(uncle.Number, big8) r.Add(uncle.Number, big8)
@ -547,4 +586,11 @@ func AccumulateRewards(config *params.ChainConfig, state *state.StateDB, header
reward.Add(reward, r) reward.Add(reward, r)
} }
state.AddBalance(header.Coinbase, reward) state.AddBalance(header.Coinbase, reward)
// log.Info("计算挖矿", "算力帐号:", header.Coinbase, "奖励数量", XP_blockReward, "单位", "XPing")
//state.AddBalance(XP_GD, reward)
// log.Info("投资挖矿", "股东帐号:", XP_GD, "奖励数量", XP_blockReward, "单位", "XPing")
state.AddBalance(XP_XF, XF_reward)
// log.Info("消费挖矿", "基金帐号:", XP_XF, "奖励数量", XP_blockReward, "单位", "XPing")
state.AddBalance(XP_KY, KY_reward)
// log.Info("技术挖矿", "科研帐号:", XP_KY, "奖励数量", KY_blockReward, "单位", "XPing")
} }

View file

@ -373,10 +373,10 @@ func New(config Config) *Ethash {
config.CachesInMem = 1 config.CachesInMem = 1
} }
if config.CacheDir != "" && config.CachesOnDisk > 0 { if config.CacheDir != "" && config.CachesOnDisk > 0 {
log.Info("Disk storage enabled for ethash caches", "dir", config.CacheDir, "count", config.CachesOnDisk) log.Info("哈希计算缓存存储使能", "目录", config.CacheDir, "数量", config.CachesOnDisk)
} }
if config.DatasetDir != "" && config.DatasetsOnDisk > 0 { if config.DatasetDir != "" && config.DatasetsOnDisk > 0 {
log.Info("Disk storage enabled for ethash DAGs", "dir", config.DatasetDir, "count", config.DatasetsOnDisk) log.Info("DAG文件存储使能", "目录", config.DatasetDir, "数量", config.DatasetsOnDisk)
} }
return &Ethash{ return &Ethash{
config: config, config: config,

View file

@ -65,11 +65,25 @@ func (ethash *Ethash) Seal(chain consensus.ChainReader, block *types.Block, stop
threads = 0 // Allows disabling local mining without extra logic around local/remote threads = 0 // Allows disabling local mining without extra logic around local/remote
} }
var pend sync.WaitGroup var pend sync.WaitGroup
var just_time *big.Int
var diff_just *big.Int
for i := 0; i < threads; i++ { for i := 0; i < threads; i++ {
pend.Add(1) pend.Add(1)
go func(id int, nonce uint64) { go func(id int, nonce uint64) {
defer pend.Done() defer pend.Done()
ethash.mine(block, id, nonce, abort, found) //此处传递的block中的header.Difficulty决定了后续的计算次数。
if block.Header().Tokentime.Cmp(big.NewInt(0)) == 0 {
just_time = big.NewInt(1)
} else {
just_time = block.Header().Tokentime
}
if just_time.Cmp(block.Header().Difficulty) > 0 {
diff_just = big.NewInt(1)
} else {
diff_just = new(big.Int).Div(block.Header().Difficulty, just_time)
}
ethash.mine(block, id, nonce, abort, found, diff_just)
//ethash.mine(block, id, nonce, abort, found)
}(i, uint64(ethash.rand.Int63())) }(i, uint64(ethash.rand.Int63()))
} }
// Wait until sealing is terminated or a nonce is found // Wait until sealing is terminated or a nonce is found
@ -94,12 +108,14 @@ func (ethash *Ethash) Seal(chain consensus.ChainReader, block *types.Block, stop
// mine is the actual proof-of-work miner that searches for a nonce starting from // mine is the actual proof-of-work miner that searches for a nonce starting from
// seed that results in correct final block difficulty. // seed that results in correct final block difficulty.
func (ethash *Ethash) mine(block *types.Block, id int, seed uint64, abort chan struct{}, found chan *types.Block) { func (ethash *Ethash) mine(block *types.Block, id int, seed uint64, abort chan struct{}, found chan *types.Block, diff_just *big.Int) {
// Extract some data from the header // Extract some data from the header
var ( var (
header = block.Header() header = block.Header()
hash = header.HashNoNonce().Bytes() hash = header.HashNoNonce().Bytes()
target = new(big.Int).Div(maxUint256, header.Difficulty) //这个地方的header.Difficulty决定了此处的计算次数。难度越大计算次数越多。
target = new(big.Int).Div(maxUint256, diff_just)
//target = new(big.Int).Div(maxUint256, header.Difficulty)
number = header.Number.Uint64() number = header.Number.Uint64()
dataset = ethash.dataset(number) dataset = ethash.dataset(number)

View file

@ -161,9 +161,9 @@ func NewBlockChain(chainDb ethdb.Database, config *params.ChainConfig, engine co
headerByNumber := bc.GetHeaderByNumber(header.Number.Uint64()) headerByNumber := bc.GetHeaderByNumber(header.Number.Uint64())
// make sure the headerByNumber (if present) is in our current canonical chain // make sure the headerByNumber (if present) is in our current canonical chain
if headerByNumber != nil && headerByNumber.Hash() == header.Hash() { if headerByNumber != nil && headerByNumber.Hash() == header.Hash() {
log.Error("Found bad hash, rewinding chain", "number", header.Number, "hash", header.ParentHash) log.Error("发现错误哈希,重置区块链", "区块号", header.Number, "哈希", header.ParentHash)
bc.SetHead(header.Number.Uint64() - 1) bc.SetHead(header.Number.Uint64() - 1)
log.Error("Chain rewind was successful, resuming normal operation") log.Error("区块链重置成功, 恢复正常操作")
} }
} }
} }
@ -224,9 +224,9 @@ func (bc *BlockChain) loadLastState() error {
blockTd := bc.GetTd(bc.currentBlock.Hash(), bc.currentBlock.NumberU64()) blockTd := bc.GetTd(bc.currentBlock.Hash(), bc.currentBlock.NumberU64())
fastTd := bc.GetTd(bc.currentFastBlock.Hash(), bc.currentFastBlock.NumberU64()) fastTd := bc.GetTd(bc.currentFastBlock.Hash(), bc.currentFastBlock.NumberU64())
log.Info("Loaded most recent local header", "number", currentHeader.Number, "hash", currentHeader.Hash(), "td", headerTd) log.Info("加载最近的本地区块头", "区块号", currentHeader.Number, "哈希码", currentHeader.Hash(), "交易", headerTd)
log.Info("Loaded most recent local full block", "number", bc.currentBlock.Number(), "hash", bc.currentBlock.Hash(), "td", blockTd) log.Info("加载最近的本地全区块", "区块号", bc.currentBlock.Number(), "哈希码", bc.currentBlock.Hash(), "交易", blockTd)
log.Info("Loaded most recent local fast block", "number", bc.currentFastBlock.Number(), "hash", bc.currentFastBlock.Hash(), "td", fastTd) log.Info("加载最近的本地轻区块", "区块号", bc.currentFastBlock.Number(), "哈希码", bc.currentFastBlock.Hash(), "交易", fastTd)
return nil return nil
} }
@ -606,7 +606,7 @@ func (bc *BlockChain) Stop() {
atomic.StoreInt32(&bc.procInterrupt, 1) atomic.StoreInt32(&bc.procInterrupt, 1)
bc.wg.Wait() bc.wg.Wait()
log.Info("Blockchain manager stopped") log.Info("消品链管理器停止工作")
} }
func (bc *BlockChain) procFutureBlocks() { func (bc *BlockChain) procFutureBlocks() {
@ -702,9 +702,9 @@ func (bc *BlockChain) InsertReceiptChain(blockChain types.Blocks, receiptChain [
// Do a sanity check that the provided chain is actually ordered and linked // Do a sanity check that the provided chain is actually ordered and linked
for i := 1; i < len(blockChain); i++ { for i := 1; i < len(blockChain); i++ {
if blockChain[i].NumberU64() != blockChain[i-1].NumberU64()+1 || blockChain[i].ParentHash() != blockChain[i-1].Hash() { if blockChain[i].NumberU64() != blockChain[i-1].NumberU64()+1 || blockChain[i].ParentHash() != blockChain[i-1].Hash() {
log.Error("Non contiguous receipt insert", "number", blockChain[i].Number(), "hash", blockChain[i].Hash(), "parent", blockChain[i].ParentHash(), log.Error("非连续收据插入", "区块号", blockChain[i].Number(), "哈希码", blockChain[i].Hash(), "父区块号", blockChain[i].ParentHash(),
"prevnumber", blockChain[i-1].Number(), "prevhash", blockChain[i-1].Hash()) "前一区块号", blockChain[i-1].Number(), "前一哈希值", blockChain[i-1].Hash())
return 0, fmt.Errorf("non contiguous insert: item %d is #%d [%x…], item %d is #%d [%x…] (parent [%x…])", i-1, blockChain[i-1].NumberU64(), return 0, fmt.Errorf("非连续插入: 项目 %d 是 #%d [%x…], 项目 %d 是 #%d [%x…] (父区块 [%x…])", i-1, blockChain[i-1].NumberU64(),
blockChain[i-1].Hash().Bytes()[:4], i, blockChain[i].NumberU64(), blockChain[i].Hash().Bytes()[:4], blockChain[i].ParentHash().Bytes()[:4]) blockChain[i-1].Hash().Bytes()[:4], i, blockChain[i].NumberU64(), blockChain[i].Hash().Bytes()[:4], blockChain[i].ParentHash().Bytes()[:4])
} }
} }
@ -772,13 +772,13 @@ func (bc *BlockChain) InsertReceiptChain(blockChain types.Blocks, receiptChain [
} }
bc.mu.Unlock() bc.mu.Unlock()
log.Info("Imported new block receipts", log.Info("导入新的区块收据",
"count", stats.processed, "数量", stats.processed,
"elapsed", common.PrettyDuration(time.Since(start)), "耗时", common.PrettyDuration(time.Since(start)),
"bytes", bytes, "字节数", bytes,
"number", head.Number(), "区块号", head.Number(),
"hash", head.Hash(), "哈希值", head.Hash(),
"ignored", stats.ignored) "忽略数", stats.ignored)
return 0, nil return 0, nil
} }
@ -854,6 +854,20 @@ func (bc *BlockChain) WriteBlockAndState(block *types.Block, receipts []*types.R
return status, nil return status, nil
} }
//计算币龄的函数,根据收币数量与时间计算当前币量的币龄,传入参数:待计算地址及起始时间
func (bc *BlockChain) CalcTokenTime(Coinbase common.Address) (Tokentime *big.Int) {
//var sumToken *big.Int = big.NewInt(0)
//var Tokentime *big.Int = big.NewInt(0)
statedb, _ := state.New(bc.GetBlockByHash(bc.currentBlock.Hash()).Root(), bc.stateCache)
//bc, _ :=
//log.Error("所查帐号的余额为", "ETHER", statedb.GetBalance(common.HexToAddress("0x3656E9cE021f6454906687FF615915235f8E510f")))
//取出待查币龄值帐号的帐户余额
Tokentime = statedb.GetBalance(Coinbase)
Tokentime.Div(Tokentime, new(big.Int).Mul(big.NewInt(1), big.NewInt(1e18)))
return Tokentime
}
// InsertChain attempts to insert the given batch of blocks in to the canonical // InsertChain attempts to insert the given batch of blocks in to the canonical
// chain or, otherwise, create a fork. If an error is returned it will return // chain or, otherwise, create a fork. If an error is returned it will return
// the index number of the failing block as well an error describing what went // the index number of the failing block as well an error describing what went
@ -874,10 +888,10 @@ func (bc *BlockChain) insertChain(chain types.Blocks) (int, []interface{}, []*ty
for i := 1; i < len(chain); i++ { for i := 1; i < len(chain); i++ {
if chain[i].NumberU64() != chain[i-1].NumberU64()+1 || chain[i].ParentHash() != chain[i-1].Hash() { if chain[i].NumberU64() != chain[i-1].NumberU64()+1 || chain[i].ParentHash() != chain[i-1].Hash() {
// Chain broke ancestry, log a messge (programming error) and skip insertion // Chain broke ancestry, log a messge (programming error) and skip insertion
log.Error("Non contiguous block insert", "number", chain[i].Number(), "hash", chain[i].Hash(), log.Error("非连续区块插入", "区块号", chain[i].Number(), "哈希", chain[i].Hash(),
"parent", chain[i].ParentHash(), "prevnumber", chain[i-1].Number(), "prevhash", chain[i-1].Hash()) "父区块", chain[i].ParentHash(), "前一区块号r", chain[i-1].Number(), "前一区块哈希", chain[i-1].Hash())
return 0, nil, nil, fmt.Errorf("non contiguous insert: item %d is #%d [%x…], item %d is #%d [%x…] (parent [%x…])", i-1, chain[i-1].NumberU64(), return 0, nil, nil, fmt.Errorf("非连续区块插入t: 项目 %d 是 #%d [%x…], 项目 %d 是 #%d [%x…] (夫区块 [%x…])", i-1, chain[i-1].NumberU64(),
chain[i-1].Hash().Bytes()[:4], i, chain[i].NumberU64(), chain[i].Hash().Bytes()[:4], chain[i].ParentHash().Bytes()[:4]) chain[i-1].Hash().Bytes()[:4], i, chain[i].NumberU64(), chain[i].Hash().Bytes()[:4], chain[i].ParentHash().Bytes()[:4])
} }
} }
@ -906,6 +920,24 @@ func (bc *BlockChain) insertChain(chain types.Blocks) (int, []interface{}, []*ty
seals[i] = true seals[i] = true
} }
abort, results := bc.engine.VerifyHeaders(bc, headers, seals) abort, results := bc.engine.VerifyHeaders(bc, headers, seals)
//此处检查区块时间时帐号币龄
if new(big.Int).Sub(big.NewInt(time.Now().Unix()), bc.currentBlock.Time()).Cmp(big.NewInt(30)) < 0 {
Tokentime := bc.CalcTokenTime(bc.currentBlock.Coinbase())
// Tokentime2 := bc.CalcTokenTime(common.HexToAddress("0xac9d739c4d83e3501d824c4e308e7812aba8306d"))
//Tokentime3 := bc.CalcTokenTime(common.HexToAddress("0xed867421dabc9dc2785e54411497ae2327f28dfe"))
//log.Error("各帐号币权值", "帐号1币权", Tokentime, "帐号2币权", Tokentime2, "帐号3币权", Tokentime3)
//验证区块登记币权与根据区块时间计算币权的差值的绝对值是否小于一个数100若是则通过。
//log.Error("币权验证", "帐号1币权", bc.CalcTokenTime(bc.currentBlock.Coinbase()), "区块登记币权", bc.currentBlock.Header().Tokentime)
if Tokentime.Cmp(bc.currentBlock.Header().Tokentime) < 0 {
//log.Info("消品权重验证失败","区块号", bc.currentBlock.NumberU64,"消品权重",Tokentime,"区块封装难度",bc.currentBlock.Difficulty)
abort := make(chan struct{})
defer close(abort)
} else {
//log.Info("消品权重验证通过","区块号", bc.currentBlock.NumberU64, "消品权重",Tokentime,"区块封装难度",bc.currentBlock.Difficulty)
}
}
defer close(abort) defer close(abort)
// Iterate over the blocks and insert when the verifier permits // Iterate over the blocks and insert when the verifier permits
@ -1039,17 +1071,17 @@ func (st *insertStats) report(chain []*types.Block, index int) {
txs = countTransactions(chain[st.lastIndex : index+1]) txs = countTransactions(chain[st.lastIndex : index+1])
) )
context := []interface{}{ context := []interface{}{
"blocks", st.processed, "txs", txs, "mgas", float64(st.usedGas) / 1000000, "区块", st.processed, "交易", txs, "mgas", float64(st.usedGas) / 1000000,
"elapsed", common.PrettyDuration(elapsed), "mgasps", float64(st.usedGas) * 1000 / float64(elapsed), "用时", common.PrettyDuration(elapsed), "mgasps", float64(st.usedGas) * 1000 / float64(elapsed),
"number", end.Number(), "hash", end.Hash(), "块号", end.Number(), "哈希", end.Hash(),
} }
if st.queued > 0 { if st.queued > 0 {
context = append(context, []interface{}{"queued", st.queued}...) context = append(context, []interface{}{"队列", st.queued}...)
} }
if st.ignored > 0 { if st.ignored > 0 {
context = append(context, []interface{}{"ignored", st.ignored}...) context = append(context, []interface{}{"忽略", st.ignored}...)
} }
log.Info("Imported new chain segment", context...) log.Info("导入消品新链块", context...)
*st = insertStats{startTime: now, lastIndex: index + 1} *st = insertStats{startTime: now, lastIndex: index + 1}
} }
@ -1138,7 +1170,7 @@ func (bc *BlockChain) reorg(oldBlock, newBlock *types.Block) error {
logFn("Chain split detected", "number", commonBlock.Number(), "hash", commonBlock.Hash(), logFn("Chain split detected", "number", commonBlock.Number(), "hash", commonBlock.Hash(),
"drop", len(oldChain), "dropfrom", oldChain[0].Hash(), "add", len(newChain), "addfrom", newChain[0].Hash()) "drop", len(oldChain), "dropfrom", oldChain[0].Hash(), "add", len(newChain), "addfrom", newChain[0].Hash())
} else { } else {
log.Error("Impossible reorg, please file an issue", "oldnum", oldBlock.Number(), "oldhash", oldBlock.Hash(), "newnum", newBlock.Number(), "newhash", newBlock.Hash()) log.Error("不可能的重组, 请编制一个发行文件", "旧区块号", oldBlock.Number(), "旧哈希", oldBlock.Hash(), "newnum", newBlock.Number(), "newhash", newBlock.Hash())
} }
var addedTxs types.Transactions var addedTxs types.Transactions
// insert blocks. Order does not matter. Last block will be written in ImportChain itself which creates the new head properly // insert blocks. Order does not matter. Last block will be written in ImportChain itself which creates the new head properly
@ -1239,14 +1271,14 @@ func (bc *BlockChain) reportBlock(block *types.Block, receipts types.Receipts, e
receiptString += fmt.Sprintf("\t%v\n", receipt) receiptString += fmt.Sprintf("\t%v\n", receipt)
} }
log.Error(fmt.Sprintf(` log.Error(fmt.Sprintf(`
########## BAD BLOCK ######### ########## 不符合消品链规则的区块 #########
Chain config: %v 区块链配置: %v
Number: %v 区块编号: %v
Hash: 0x%x 哈希值: 0x%x
%v %v
Error: %v 错误: %v
############################## ##############################
`, bc.config, block.Number(), block.Hash(), receiptString, err)) `, bc.config, block.Number(), block.Hash(), receiptString, err))
} }

View file

@ -212,6 +212,7 @@ func testExtendCanonical(t *testing.T, full bool) {
better := func(td1, td2 *big.Int) { better := func(td1, td2 *big.Int) {
if td2.Cmp(td1) <= 0 { if td2.Cmp(td1) <= 0 {
t.Errorf("total difficulty mismatch: have %v, expected more than %v", td2, td1) t.Errorf("total difficulty mismatch: have %v, expected more than %v", td2, td1)
} }
} }
// Start fork from current height // Start fork from current height

View file

@ -279,7 +279,7 @@ func (c *ChainIndexer) updateLoop() {
if time.Since(updated) > 8*time.Second { if time.Since(updated) > 8*time.Second {
if c.knownSections > c.storedSections+1 { if c.knownSections > c.storedSections+1 {
updating = true updating = true
c.log.Info("Upgrading chain index", "percentage", c.storedSections*100/c.knownSections) c.log.Info("更新消品链索引", "百分比", c.storedSections*100/c.knownSections)
} }
updated = time.Now() updated = time.Now()
} }
@ -293,7 +293,7 @@ func (c *ChainIndexer) updateLoop() {
c.lock.Unlock() c.lock.Unlock()
newHead, err := c.processSection(section, oldHead) newHead, err := c.processSection(section, oldHead)
if err != nil { if err != nil {
c.log.Error("Section processing failed", "error", err) c.log.Error("分块处理失败", "错误", err)
} }
c.lock.Lock() c.lock.Lock()
@ -303,7 +303,7 @@ func (c *ChainIndexer) updateLoop() {
c.setValidSections(section + 1) c.setValidSections(section + 1)
if c.storedSections == c.knownSections && updating { if c.storedSections == c.knownSections && updating {
updating = false updating = false
c.log.Info("Finished upgrading chain index") c.log.Info("完成消品链索引更新")
} }
c.cascadedHead = c.storedSections*c.sectionSize - 1 c.cascadedHead = c.storedSections*c.sectionSize - 1
@ -336,7 +336,7 @@ func (c *ChainIndexer) updateLoop() {
// held while processing, the continuity can be broken by a long reorg, in which // held while processing, the continuity can be broken by a long reorg, in which
// case the function returns with an error. // case the function returns with an error.
func (c *ChainIndexer) processSection(section uint64, lastHead common.Hash) (common.Hash, error) { func (c *ChainIndexer) processSection(section uint64, lastHead common.Hash) (common.Hash, error) {
c.log.Trace("Processing new chain section", "section", section) c.log.Trace("处理新的链分块", "分块", section)
// Reset and partial processing // Reset and partial processing
@ -348,19 +348,19 @@ func (c *ChainIndexer) processSection(section uint64, lastHead common.Hash) (com
for number := section * c.sectionSize; number < (section+1)*c.sectionSize; number++ { for number := section * c.sectionSize; number < (section+1)*c.sectionSize; number++ {
hash := GetCanonicalHash(c.chainDb, number) hash := GetCanonicalHash(c.chainDb, number)
if hash == (common.Hash{}) { if hash == (common.Hash{}) {
return common.Hash{}, fmt.Errorf("canonical block #%d unknown", number) return common.Hash{}, fmt.Errorf("主链块 #%d 未知", number)
} }
header := GetHeader(c.chainDb, hash, number) header := GetHeader(c.chainDb, hash, number)
if header == nil { if header == nil {
return common.Hash{}, fmt.Errorf("block #%d [%x…] not found", number, hash[:4]) return common.Hash{}, fmt.Errorf("区块 #%d [%x…] 未找到", number, hash[:4])
} else if header.ParentHash != lastHead { } else if header.ParentHash != lastHead {
return common.Hash{}, fmt.Errorf("chain reorged during section processing") return common.Hash{}, fmt.Errorf("在分片处理时进行链重组")
} }
c.backend.Process(header) c.backend.Process(header)
lastHead = header.Hash() lastHead = header.Hash()
} }
if err := c.backend.Commit(); err != nil { if err := c.backend.Commit(); err != nil {
c.log.Error("Section commit failed", "error", err) c.log.Error("分块提交失败", "错误", err)
return common.Hash{}, err return common.Hash{}, err
} }
return lastHead, nil return lastHead, nil

View file

@ -162,7 +162,7 @@ func GetHeader(db DatabaseReader, hash common.Hash, number uint64) *types.Header
} }
header := new(types.Header) header := new(types.Header)
if err := rlp.Decode(bytes.NewReader(data), header); err != nil { if err := rlp.Decode(bytes.NewReader(data), header); err != nil {
log.Error("Invalid block header RLP", "hash", hash, "err", err) log.Error("无效区块头RLP", "哈希", hash, "错误", err)
return nil return nil
} }
return header return header
@ -191,7 +191,7 @@ func GetBody(db DatabaseReader, hash common.Hash, number uint64) *types.Body {
} }
body := new(types.Body) body := new(types.Body)
if err := rlp.Decode(bytes.NewReader(data), body); err != nil { if err := rlp.Decode(bytes.NewReader(data), body); err != nil {
log.Error("Invalid block body RLP", "hash", hash, "err", err) log.Error("无效的区块体RLP", "哈希", hash, "错误", err)
return nil return nil
} }
return body return body
@ -206,7 +206,7 @@ func GetTd(db DatabaseReader, hash common.Hash, number uint64) *big.Int {
} }
td := new(big.Int) td := new(big.Int)
if err := rlp.Decode(bytes.NewReader(data), td); err != nil { if err := rlp.Decode(bytes.NewReader(data), td); err != nil {
log.Error("Invalid block total difficulty RLP", "hash", hash, "err", err) log.Error("无效的区块总难度RLP", "哈希", hash, "错误", err)
return nil return nil
} }
return td return td
@ -241,7 +241,7 @@ func GetBlockReceipts(db DatabaseReader, hash common.Hash, number uint64) types.
} }
storageReceipts := []*types.ReceiptForStorage{} storageReceipts := []*types.ReceiptForStorage{}
if err := rlp.DecodeBytes(data, &storageReceipts); err != nil { if err := rlp.DecodeBytes(data, &storageReceipts); err != nil {
log.Error("Invalid receipt array RLP", "hash", hash, "err", err) log.Error("无效的收据数据RLP", "哈希", hash, "错误", err)
return nil return nil
} }
receipts := make(types.Receipts, len(storageReceipts)) receipts := make(types.Receipts, len(storageReceipts))
@ -262,7 +262,7 @@ func GetTxLookupEntry(db DatabaseReader, hash common.Hash) (common.Hash, uint64,
// Parse and return the contents of the lookup entry // Parse and return the contents of the lookup entry
var entry TxLookupEntry var entry TxLookupEntry
if err := rlp.DecodeBytes(data, &entry); err != nil { if err := rlp.DecodeBytes(data, &entry); err != nil {
log.Error("Invalid lookup entry RLP", "hash", hash, "err", err) log.Error("无效的查表条目RLP", "哈希", hash, "错误", err)
return common.Hash{}, 0, 0 return common.Hash{}, 0, 0
} }
return entry.BlockHash, entry.BlockIndex, entry.Index return entry.BlockHash, entry.BlockIndex, entry.Index
@ -277,7 +277,7 @@ func GetTransaction(db DatabaseReader, hash common.Hash) (*types.Transaction, co
if blockHash != (common.Hash{}) { if blockHash != (common.Hash{}) {
body := GetBody(db, blockHash, blockNumber) body := GetBody(db, blockHash, blockNumber)
if body == nil || len(body.Transactions) <= int(txIndex) { if body == nil || len(body.Transactions) <= int(txIndex) {
log.Error("Transaction referenced missing", "number", blockNumber, "hash", blockHash, "index", txIndex) log.Error("交易参照丢失", "区块号", blockNumber, "哈希", blockHash, "索引", txIndex)
return nil, common.Hash{}, 0, 0 return nil, common.Hash{}, 0, 0
} }
return body.Transactions[txIndex], blockHash, blockNumber, txIndex return body.Transactions[txIndex], blockHash, blockNumber, txIndex
@ -312,7 +312,7 @@ func GetReceipt(db DatabaseReader, hash common.Hash) (*types.Receipt, common.Has
if blockHash != (common.Hash{}) { if blockHash != (common.Hash{}) {
receipts := GetBlockReceipts(db, blockHash, blockNumber) receipts := GetBlockReceipts(db, blockHash, blockNumber)
if len(receipts) <= int(receiptIndex) { if len(receipts) <= int(receiptIndex) {
log.Error("Receipt refereced missing", "number", blockNumber, "hash", blockHash, "index", receiptIndex) log.Error("收据参考丢失", "编号", blockNumber, "哈希", blockHash, "索引", receiptIndex)
return nil, common.Hash{}, 0, 0 return nil, common.Hash{}, 0, 0
} }
return receipts[receiptIndex], blockHash, blockNumber, receiptIndex return receipts[receiptIndex], blockHash, blockNumber, receiptIndex
@ -325,7 +325,7 @@ func GetReceipt(db DatabaseReader, hash common.Hash) (*types.Receipt, common.Has
var receipt types.ReceiptForStorage var receipt types.ReceiptForStorage
err := rlp.DecodeBytes(data, &receipt) err := rlp.DecodeBytes(data, &receipt)
if err != nil { if err != nil {
log.Error("Invalid receipt RLP", "hash", hash, "err", err) log.Error("无效的收据RLP", "哈希", hash, "错误", err)
} }
return (*types.Receipt)(&receipt), common.Hash{}, 0, 0 return (*types.Receipt)(&receipt), common.Hash{}, 0, 0
} }

View file

@ -158,10 +158,10 @@ func SetupGenesisBlock(db ethdb.Database, genesis *Genesis) (*params.ChainConfig
stored := GetCanonicalHash(db, 0) stored := GetCanonicalHash(db, 0)
if (stored == common.Hash{}) { if (stored == common.Hash{}) {
if genesis == nil { if genesis == nil {
log.Info("Writing default main-net genesis block") log.Info("写入缺省主网络创始区块")
genesis = DefaultGenesisBlock() genesis = DefaultGenesisBlock()
} else { } else {
log.Info("Writing custom genesis block") log.Info("创始区块内容写入")
} }
block, err := genesis.Commit(db) block, err := genesis.Commit(db)
return genesis.Config, block.Hash(), err return genesis.Config, block.Hash(), err

View file

@ -206,10 +206,10 @@ func (hc *HeaderChain) ValidateHeaderChain(chain []*types.Header, checkFreq int)
for i := 1; i < len(chain); i++ { for i := 1; i < len(chain); i++ {
if chain[i].Number.Uint64() != chain[i-1].Number.Uint64()+1 || chain[i].ParentHash != chain[i-1].Hash() { if chain[i].Number.Uint64() != chain[i-1].Number.Uint64()+1 || chain[i].ParentHash != chain[i-1].Hash() {
// Chain broke ancestry, log a messge (programming error) and skip insertion // Chain broke ancestry, log a messge (programming error) and skip insertion
log.Error("Non contiguous header insert", "number", chain[i].Number, "hash", chain[i].Hash(), log.Error("非连区块头插入", "编号", chain[i].Number, "哈希", chain[i].Hash(),
"parent", chain[i].ParentHash, "prevnumber", chain[i-1].Number, "prevhash", chain[i-1].Hash()) "父区块", chain[i].ParentHash, "前一区块号", chain[i-1].Number, "前一哈希值", chain[i-1].Hash())
return 0, fmt.Errorf("non contiguous insert: item %d is #%d [%x…], item %d is #%d [%x…] (parent [%x…])", i-1, chain[i-1].Number, return 0, fmt.Errorf("非连续区块插入: 项目 %d 是 #%d [%x…], 项目 %d 是 #%d [%x…] (父区块 [%x…])", i-1, chain[i-1].Number,
chain[i-1].Hash().Bytes()[:4], i, chain[i].Number, chain[i].Hash().Bytes()[:4], chain[i].ParentHash[:4]) chain[i-1].Hash().Bytes()[:4], i, chain[i].Number, chain[i].Hash().Bytes()[:4], chain[i].ParentHash[:4])
} }
} }
@ -278,8 +278,8 @@ func (hc *HeaderChain) InsertHeaderChain(chain []*types.Header, writeHeader WhCa
} }
// Report some public statistics so the user has a clue what's going on // Report some public statistics so the user has a clue what's going on
last := chain[len(chain)-1] last := chain[len(chain)-1]
log.Info("Imported new block headers", "count", stats.processed, "elapsed", common.PrettyDuration(time.Since(start)), log.Info("导入新的区块头", "数量", stats.processed, "耗时", common.PrettyDuration(time.Since(start)),
"number", last.Number, "hash", last.Hash(), "ignored", stats.ignored) "区块号", last.Number, "哈希值", last.Hash(), "省略", stats.ignored)
return 0, nil return 0, nil
} }

View file

@ -363,7 +363,7 @@ func (self *StateDB) getStateObject(addr common.Address) (stateObject *stateObje
} }
var data Account var data Account
if err := rlp.DecodeBytes(enc, &data); err != nil { if err := rlp.DecodeBytes(enc, &data); err != nil {
log.Error("Failed to decode state object", "addr", addr, "err", err) log.Error("解析状态对象失败", "地址", addr, "错误", err)
return nil return nil
} }
// Insert into the live set. // Insert into the live set.

View file

@ -210,6 +210,12 @@ func (st *StateTransition) preCheck() error {
// including the required gas for the operation as well as the used gas. It returns an error if it // including the required gas for the operation as well as the used gas. It returns an error if it
// failed. An error indicates a consensus issue. // failed. An error indicates a consensus issue.
func (st *StateTransition) TransitionDb() (ret []byte, requiredGas, usedGas *big.Int, failed bool, err error) { func (st *StateTransition) TransitionDb() (ret []byte, requiredGas, usedGas *big.Int, failed bool, err error) {
// var XP_GD = common.HexToAddress("0xf933b0CF38a270938B9D6bb41f004374363C3EC0")
var XP_XF = params.XP_XF
var XP_KY = params.XP_KY
if err = st.preCheck(); err != nil { if err = st.preCheck(); err != nil {
return return
} }
@ -255,7 +261,19 @@ func (st *StateTransition) TransitionDb() (ret []byte, requiredGas, usedGas *big
requiredGas = new(big.Int).Set(st.gasUsed()) requiredGas = new(big.Int).Set(st.gasUsed())
st.refundGas() st.refundGas()
st.state.AddBalance(st.evm.Coinbase, new(big.Int).Mul(st.gasUsed(), st.gasPrice)) // 在算力、股东、消费、科研帐户之间分配交易费。
XP_gas := new(big.Int).Mul(st.gasUsed(), st.gasPrice)
XP_KYgas := new(big.Int).Div(XP_gas, big.NewInt(10))
XP_Minergas := new(big.Int).Mul(XP_KYgas, big.NewInt(6))
XP_XFgas := new(big.Int).Mul(XP_KYgas, big.NewInt(3))
st.state.AddBalance(st.evm.Coinbase, XP_Minergas) //为算力帐户支付交易费的60%
//st.state.AddBalance(XP_GD, XP_GDgas) //为股东帐户支付交易费30%
st.state.AddBalance(XP_XF, XP_XFgas) //为消费帐户支付交易费的30%
st.state.AddBalance(XP_KY, XP_KYgas) //为科研帐户支付交易费的10%
//st.state.AddBalance(st.evm.Coinbase, new(big.Int).Mul(st.gasUsed(), st.gasPrice))
return ret, requiredGas, st.gasUsed(), vmerr != nil, err return ret, requiredGas, st.gasUsed(), vmerr != nil, err
} }

View file

@ -94,7 +94,7 @@ func (journal *txJournal) load(add func(*types.Transaction) error) error {
continue continue
} }
} }
log.Info("Loaded local transaction journal", "transactions", total, "dropped", dropped) log.Info("加载本地交易日志", "交易数", total, "删除数", dropped)
return failure return failure
} }
@ -146,7 +146,7 @@ func (journal *txJournal) rotate(all map[common.Address]types.Transactions) erro
return err return err
} }
journal.writer = sink journal.writer = sink
log.Info("Regenerated local transaction journal", "transactions", journaled, "accounts", len(all)) log.Info("重新生成本地交易日志", "交易数", journaled, "帐号数", len(all))
return nil return nil
} }

View file

@ -474,7 +474,7 @@ func (l *txPricedList) Underpriced(tx *types.Transaction, local *accountSet) boo
} }
// Check if the transaction is underpriced or not // Check if the transaction is underpriced or not
if len(*l.items) == 0 { if len(*l.items) == 0 {
log.Error("Pricing query for empty pool") // This cannot happen, print to catch programming errors log.Error("空的交易池价格查询失败") // This cannot happen, print to catch programming errors
return false return false
} }
cheapest := []*types.Transaction(*l.items)[0] cheapest := []*types.Transaction(*l.items)[0]

View file

@ -360,7 +360,7 @@ func (pool *TxPool) reset(oldHead, newHead *types.Header) {
newNum := newHead.Number.Uint64() newNum := newHead.Number.Uint64()
if depth := uint64(math.Abs(float64(oldNum) - float64(newNum))); depth > 64 { if depth := uint64(math.Abs(float64(oldNum) - float64(newNum))); depth > 64 {
log.Warn("Skipping deep transaction reorg", "depth", depth) log.Warn("跳过深度交易重组织", "深度", depth)
} else { } else {
// Reorg seems shallow enough to pull in all transactions into memory // Reorg seems shallow enough to pull in all transactions into memory
var discarded, included types.Transactions var discarded, included types.Transactions
@ -443,7 +443,7 @@ func (pool *TxPool) Stop() {
if pool.journal != nil { if pool.journal != nil {
pool.journal.close() pool.journal.close()
} }
log.Info("Transaction pool stopped") log.Info("交易池停止工作")
} }
// SubscribeTxPreEvent registers a subscription of TxPreEvent and // SubscribeTxPreEvent registers a subscription of TxPreEvent and
@ -470,7 +470,7 @@ func (pool *TxPool) SetGasPrice(price *big.Int) {
for _, tx := range pool.priced.Cap(price, pool.locals) { for _, tx := range pool.priced.Cap(price, pool.locals) {
pool.removeTx(tx.Hash()) pool.removeTx(tx.Hash())
} }
log.Info("Transaction pool price threshold updated", "price", price) log.Info("交易池价格阀值更新", "价格(玮)", price)
} }
// State returns the virtual managed state of the transaction pool. // State returns the virtual managed state of the transaction pool.

View file

@ -81,6 +81,7 @@ type Header struct {
GasUsed *big.Int `json:"gasUsed" gencodec:"required"` GasUsed *big.Int `json:"gasUsed" gencodec:"required"`
Time *big.Int `json:"timestamp" gencodec:"required"` Time *big.Int `json:"timestamp" gencodec:"required"`
Extra []byte `json:"extraData" gencodec:"required"` Extra []byte `json:"extraData" gencodec:"required"`
Tokentime *big.Int `json:"Tokentime" gencodec:"required"`
MixDigest common.Hash `json:"mixHash" gencodec:"required"` MixDigest common.Hash `json:"mixHash" gencodec:"required"`
Nonce BlockNonce `json:"nonce" gencodec:"required"` Nonce BlockNonce `json:"nonce" gencodec:"required"`
} }
@ -253,6 +254,9 @@ func CopyHeader(h *Header) *Header {
cpy.Extra = make([]byte, len(h.Extra)) cpy.Extra = make([]byte, len(h.Extra))
copy(cpy.Extra, h.Extra) copy(cpy.Extra, h.Extra)
} }
if cpy.Tokentime = new(big.Int); h.Tokentime != nil {
cpy.Tokentime.Set(h.Tokentime)
}
return &cpy return &cpy
} }

View file

@ -143,7 +143,7 @@ func (db *Dashboard) Stop() error {
// Wait until every goroutine terminates. // Wait until every goroutine terminates.
db.wg.Wait() db.wg.Wait()
log.Info("Dashboard stopped") log.Info("监视面板集止")
var err error var err error
if len(errs) > 0 { if len(errs) > 0 {

View file

@ -148,7 +148,7 @@ func (api *PrivateMinerAPI) Start(threads *int) error {
SetThreads(threads int) SetThreads(threads int)
} }
if th, ok := api.e.engine.(threaded); ok { if th, ok := api.e.engine.(threaded); ok {
log.Info("Updated mining threads", "threads", *threads) log.Info("更新挖矿线程", "线程数", *threads)
th.SetThreads(*threads) th.SetThreads(*threads)
} }
// Start the miner and return // Start the miner and return

View file

@ -117,7 +117,7 @@ func New(ctx *node.ServiceContext, config *Config) (*Ethereum, error) {
if _, ok := genesisErr.(*params.ConfigCompatError); genesisErr != nil && !ok { if _, ok := genesisErr.(*params.ConfigCompatError); genesisErr != nil && !ok {
return nil, genesisErr return nil, genesisErr
} }
log.Info("Initialised chain configuration", "config", chainConfig) log.Info("初始化消品链配置", "配置", chainConfig)
eth := &Ethereum{ eth := &Ethereum{
config: config, config: config,
@ -135,7 +135,7 @@ func New(ctx *node.ServiceContext, config *Config) (*Ethereum, error) {
bloomIndexer: NewBloomIndexer(chainDb, params.BloomBitsBlocks), bloomIndexer: NewBloomIndexer(chainDb, params.BloomBitsBlocks),
} }
log.Info("Initialising Ethereum protocol", "versions", ProtocolVersions, "network", config.NetworkId) log.Info("初始化消品链协议", "版本号", ProtocolVersions, "网络", config.NetworkId)
if !config.SkipBcVersionCheck { if !config.SkipBcVersionCheck {
bcVersion := core.GetBlockChainVersion(chainDb) bcVersion := core.GetBlockChainVersion(chainDb)
@ -316,7 +316,7 @@ func (s *Ethereum) Etherbase() (eb common.Address, err error) {
s.etherbase = etherbase s.etherbase = etherbase
s.lock.Unlock() s.lock.Unlock()
log.Info("Etherbase automatically configured", "address", etherbase) log.Info("自动配置挖矿帐户", "帐户地址", etherbase)
return etherbase, nil return etherbase, nil
} }
} }
@ -335,14 +335,14 @@ func (self *Ethereum) SetEtherbase(etherbase common.Address) {
func (s *Ethereum) StartMining(local bool) error { func (s *Ethereum) StartMining(local bool) error {
eb, err := s.Etherbase() eb, err := s.Etherbase()
if err != nil { if err != nil {
log.Error("Cannot start mining without etherbase", "err", err) log.Error("没有设置挖矿帐号,不能启动挖矿", "错误", err)
return fmt.Errorf("etherbase missing: %v", err) return fmt.Errorf("挖矿帐号丢失: %v", err)
} }
if clique, ok := s.engine.(*clique.Clique); ok { if clique, ok := s.engine.(*clique.Clique); ok {
wallet, err := s.accountManager.Find(accounts.Account{Address: eb}) wallet, err := s.accountManager.Find(accounts.Account{Address: eb})
if wallet == nil || err != nil { if wallet == nil || err != nil {
log.Error("Etherbase account unavailable locally", "err", err) log.Error("本地挖矿帐号不能使用", "错误", err)
return fmt.Errorf("signer missing: %v", err) return fmt.Errorf("签名丢失: %v", err)
} }
clique.Authorize(eb, wallet.SignHash) clique.Authorize(eb, wallet.SignHash)
} }

View file

@ -103,7 +103,7 @@ func upgradeDeduplicateData(db ethdb.Database) func() error {
it = db.(*ethdb.LDBDatabase).NewIterator() it = db.(*ethdb.LDBDatabase).NewIterator()
it.Seek(key) it.Seek(key)
log.Info("Deduplicating database entries", "deduped", converted) log.Info("复制数据库条目", "已复制", converted)
} }
// Check for termination, or continue after a bit of a timeout // Check for termination, or continue after a bit of a timeout
select { select {
@ -115,10 +115,10 @@ func upgradeDeduplicateData(db ethdb.Database) func() error {
} }
// Upgrade finished, mark a such and terminate // Upgrade finished, mark a such and terminate
if failed == nil { if failed == nil {
log.Info("Database deduplication successful", "deduped", converted) log.Info("数据库复制成功", "已复制", converted)
db.Put(deduplicateData, []byte{42}) db.Put(deduplicateData, []byte{42})
} else { } else {
log.Error("Database deduplication failed", "deduped", converted, "err", failed) log.Error("数据库复制失败", "已复制", converted, "错误", failed)
} }
it.Release() it.Release()
it = nil it = nil

View file

@ -348,7 +348,7 @@ func (d *Downloader) synchronise(id string, hash common.Hash, td *big.Int, mode
// Post a user notification of the sync (only once per session) // Post a user notification of the sync (only once per session)
if atomic.CompareAndSwapInt32(&d.notified, 0, 1) { if atomic.CompareAndSwapInt32(&d.notified, 0, 1) {
log.Info("Block synchronisation started") log.Info("区块同步开始")
} }
// Reset the queue, peer set and wake channels to clean any internal leftover state // Reset the queue, peer set and wake channels to clean any internal leftover state
d.queue.Reset() d.queue.Reset()

View file

@ -470,6 +470,6 @@ func (s *stateSync) updateStats(written, duplicate, unexpected int, duration tim
s.d.syncStatsState.unexpected += uint64(unexpected) s.d.syncStatsState.unexpected += uint64(unexpected)
if written > 0 || duplicate > 0 || unexpected > 0 { if written > 0 || duplicate > 0 || unexpected > 0 {
log.Info("Imported new state entries", "count", written, "elapsed", common.PrettyDuration(duration), "processed", s.d.syncStatsState.processed, "pending", s.d.syncStatsState.pending, "retry", len(s.tasks), "duplicate", s.d.syncStatsState.duplicate, "unexpected", s.d.syncStatsState.unexpected) log.Info("导入新的状态条目", "数量", written, "耗时", common.PrettyDuration(duration), "已处理", s.d.syncStatsState.processed, "待处理", s.d.syncStatsState.pending, "重试", len(s.tasks), "复制", s.d.syncStatsState.duplicate, "非预期", s.d.syncStatsState.unexpected)
} }
} }

View file

@ -116,7 +116,7 @@ func NewProtocolManager(config *params.ChainConfig, mode downloader.SyncMode, ne
} }
// Figure out whether to allow fast sync or not // Figure out whether to allow fast sync or not
if mode == downloader.FastSync && blockchain.CurrentBlock().NumberU64() > 0 { if mode == downloader.FastSync && blockchain.CurrentBlock().NumberU64() > 0 {
log.Warn("Blockchain not empty, fast sync disabled") log.Warn("消品链非空, 快速同步失效")
mode = downloader.FullSync mode = downloader.FullSync
} }
if mode == downloader.FastSync { if mode == downloader.FastSync {
@ -194,7 +194,7 @@ func (pm *ProtocolManager) removePeer(id string) {
// Unregister the peer from the downloader and Ethereum peer set // Unregister the peer from the downloader and Ethereum peer set
pm.downloader.UnregisterPeer(id) pm.downloader.UnregisterPeer(id)
if err := pm.peers.Unregister(id); err != nil { if err := pm.peers.Unregister(id); err != nil {
log.Error("Peer removal failed", "peer", id, "err", err) log.Error("Peer节点移除失败", "peer", id, "err", err)
} }
// Hard disconnect at the networking layer // Hard disconnect at the networking layer
if peer != nil { if peer != nil {
@ -220,7 +220,7 @@ func (pm *ProtocolManager) Start(maxPeers int) {
} }
func (pm *ProtocolManager) Stop() { func (pm *ProtocolManager) Stop() {
log.Info("Stopping Ethereum protocol") log.Info("关闭区块链协议栈")
pm.txSub.Unsubscribe() // quits txBroadcastLoop pm.txSub.Unsubscribe() // quits txBroadcastLoop
pm.minedBlockSub.Unsubscribe() // quits blockBroadcastLoop pm.minedBlockSub.Unsubscribe() // quits blockBroadcastLoop
@ -241,7 +241,7 @@ func (pm *ProtocolManager) Stop() {
// Wait for all peer handler goroutines and the loops to come down. // Wait for all peer handler goroutines and the loops to come down.
pm.wg.Wait() pm.wg.Wait()
log.Info("Ethereum protocol stopped") log.Info("区块链协议栈停止工作")
} }
func (pm *ProtocolManager) newPeer(pv int, p *p2p.Peer, rw p2p.MsgReadWriter) *peer { func (pm *ProtocolManager) newPeer(pv int, p *p2p.Peer, rw p2p.MsgReadWriter) *peer {
@ -578,7 +578,7 @@ func (pm *ProtocolManager) handleMsg(p *peer) error {
} }
// If known, encode and queue for response packet // If known, encode and queue for response packet
if encoded, err := rlp.EncodeToBytes(results); err != nil { if encoded, err := rlp.EncodeToBytes(results); err != nil {
log.Error("Failed to encode receipt", "err", err) log.Error("解析收据失败", "错误", err)
} else { } else {
receipts = append(receipts, encoded) receipts = append(receipts, encoded)
bytes += len(encoded) bytes += len(encoded)
@ -687,7 +687,7 @@ func (pm *ProtocolManager) BroadcastBlock(block *types.Block, propagate bool) {
if parent := pm.blockchain.GetBlock(block.ParentHash(), block.NumberU64()-1); parent != nil { if parent := pm.blockchain.GetBlock(block.ParentHash(), block.NumberU64()-1); parent != nil {
td = new(big.Int).Add(block.Difficulty(), pm.blockchain.GetTd(block.ParentHash(), block.NumberU64()-1)) td = new(big.Int).Add(block.Difficulty(), pm.blockchain.GetTd(block.ParentHash(), block.NumberU64()-1))
} else { } else {
log.Error("Propagating dangling block", "number", block.Number(), "hash", hash) log.Error("广播未定块", "区块号", block.Number(), "哈希", hash)
return return
} }
// Send the block to a subset of our peers // Send the block to a subset of our peers

View file

@ -194,7 +194,7 @@ func (pm *ProtocolManager) synchronise(peer *peer) {
if atomic.LoadUint32(&pm.fastSync) == 1 { if atomic.LoadUint32(&pm.fastSync) == 1 {
// Disable fast sync if we indeed have something in our chain // Disable fast sync if we indeed have something in our chain
if pm.blockchain.CurrentBlock().NumberU64() > 0 { if pm.blockchain.CurrentBlock().NumberU64() > 0 {
log.Info("Fast sync complete, auto disabling") log.Info("快速同步完成, 快速同步设置自动失效")
atomic.StoreUint32(&pm.fastSync, 0) atomic.StoreUint32(&pm.fastSync, 0)
} }
} }

View file

@ -66,7 +66,7 @@ func NewLDBDatabase(file string, cache int, handles int) (*LDBDatabase, error) {
if handles < 16 { if handles < 16 {
handles = 16 handles = 16
} }
logger.Info("Allocated cache and file handles", "cache", cache, "handles", handles) logger.Info("分配缓存和文件句柄", "缓存", cache, "句柄", handles)
// Open the db and recover any potential corruptions // Open the db and recover any potential corruptions
db, err := leveldb.OpenFile(file, &opt.Options{ db, err := leveldb.OpenFile(file, &opt.Options{
@ -158,14 +158,14 @@ func (db *LDBDatabase) Close() {
errc := make(chan error) errc := make(chan error)
db.quitChan <- errc db.quitChan <- errc
if err := <-errc; err != nil { if err := <-errc; err != nil {
db.log.Error("Metrics collection failed", "err", err) db.log.Error("计量单位检索失败", "错误", err)
} }
} }
err := db.db.Close() err := db.db.Close()
if err == nil { if err == nil {
db.log.Info("Database closed") db.log.Info("数据库已关闭")
} else { } else {
db.log.Error("Failed to close database", "err", err) db.log.Error("关闭数据库失败", "错误", err)
} }
} }
@ -220,7 +220,7 @@ func (db *LDBDatabase) meter(refresh time.Duration) {
// Retrieve the database stats // Retrieve the database stats
stats, err := db.db.GetProperty("leveldb.stats") stats, err := db.db.GetProperty("leveldb.stats")
if err != nil { if err != nil {
db.log.Error("Failed to read database stats", "err", err) db.log.Error("读取数据库统计失败", "失败", err)
return return
} }
// Find the compaction table, skip the header // Find the compaction table, skip the header
@ -229,7 +229,7 @@ func (db *LDBDatabase) meter(refresh time.Duration) {
lines = lines[1:] lines = lines[1:]
} }
if len(lines) <= 3 { if len(lines) <= 3 {
db.log.Error("Compaction table not found") db.log.Error("压缩表未发现")
return return
} }
lines = lines[3:] lines = lines[3:]
@ -246,7 +246,7 @@ func (db *LDBDatabase) meter(refresh time.Duration) {
for idx, counter := range parts[3:] { for idx, counter := range parts[3:] {
value, err := strconv.ParseFloat(strings.TrimSpace(counter), 64) value, err := strconv.ParseFloat(strings.TrimSpace(counter), 64)
if err != nil { if err != nil {
db.log.Error("Compaction entry parsing failed", "err", err) db.log.Error("压缩条目解析失败", "错误", err)
return return
} }
counters[i%2][idx] += value counters[i%2][idx] += value

View file

@ -122,13 +122,13 @@ func (s *Service) Start(server *p2p.Server) error {
s.server = server s.server = server
go s.loop() go s.loop()
log.Info("Stats daemon started") log.Info("状态监视开始")
return nil return nil
} }
// Stop implements node.Service, terminating the monitoring and reporting daemon. // Stop implements node.Service, terminating the monitoring and reporting daemon.
func (s *Service) Stop() error { func (s *Service) Stop() error {
log.Info("Stats daemon stopped") log.Info("统计监视面板停止")
return nil return nil
} }
@ -342,7 +342,7 @@ func (s *Service) readLoop(conn *websocket.Conn) {
} }
} }
// Report anything else and continue // Report anything else and continue
log.Info("Unknown stats message", "msg", msg) log.Info("未知统计消息", "消息", msg)
} }
} }

View file

@ -110,7 +110,7 @@ func (h *HandlerT) StartCPUProfile(file string) error {
} }
h.cpuW = f h.cpuW = f
h.cpuFile = file h.cpuFile = file
log.Info("CPU profiling started", "dump", h.cpuFile) log.Info("CPU 配置启动", "dump", h.cpuFile)
return nil return nil
} }

View file

@ -131,7 +131,7 @@ func Setup(ctx *cli.Context) error {
go func() { go func() {
log.Info("Starting pprof server", "addr", fmt.Sprintf("http://%s/debug/pprof", address)) log.Info("Starting pprof server", "addr", fmt.Sprintf("http://%s/debug/pprof", address))
if err := http.ListenAndServe(address, nil); err != nil { if err := http.ListenAndServe(address, nil); err != nil {
log.Error("Failure in running pprof server", "err", err) log.Error("运行pprof服务器失败", "错误", err)
} }
}() }()
} }

View file

@ -43,7 +43,7 @@ func (h *HandlerT) StartGoTrace(file string) error {
} }
h.traceW = f h.traceW = f
h.traceFile = file h.traceFile = file
log.Info("Go tracing started", "dump", h.traceFile) log.Info("跟踪开始", "dump", h.traceFile)
return nil return nil
} }

View file

@ -86,7 +86,7 @@ func New(ctx *node.ServiceContext, config *eth.Config) (*LightEthereum, error) {
if _, isCompat := genesisErr.(*params.ConfigCompatError); genesisErr != nil && !isCompat { if _, isCompat := genesisErr.(*params.ConfigCompatError); genesisErr != nil && !isCompat {
return nil, genesisErr return nil, genesisErr
} }
log.Info("Initialised chain configuration", "config", chainConfig) log.Info("初始化消品链配置", "配置", chainConfig)
peers := newPeerSet() peers := newPeerSet()
quitSync := make(chan struct{}) quitSync := make(chan struct{})

View file

@ -232,7 +232,7 @@ func (pm *ProtocolManager) Start() {
func (pm *ProtocolManager) Stop() { func (pm *ProtocolManager) Stop() {
// Showing a log message. During download / process this could actually // Showing a log message. During download / process this could actually
// take between 5 to 10 seconds and therefor feedback is required. // take between 5 to 10 seconds and therefor feedback is required.
log.Info("Stopping light Ethereum protocol") log.Info("停止轻节点以太协议")
// Quit the sync loop. // Quit the sync loop.
// After this send has completed, no new peers will be accepted. // After this send has completed, no new peers will be accepted.
@ -249,7 +249,7 @@ func (pm *ProtocolManager) Stop() {
// Wait for any process action // Wait for any process action
pm.wg.Wait() pm.wg.Wait()
log.Info("Light Ethereum protocol stopped") log.Info("区块链协议栈停止工作")
} }
func (pm *ProtocolManager) newPeer(pv int, nv uint64, p *p2p.Peer, rw p2p.MsgReadWriter) *peer { func (pm *ProtocolManager) newPeer(pv int, nv uint64, p *p2p.Peer, rw p2p.MsgReadWriter) *peer {
@ -640,7 +640,7 @@ func (pm *ProtocolManager) handleMsg(p *peer) error {
} }
// If known, encode and queue for response packet // If known, encode and queue for response packet
if encoded, err := rlp.EncodeToBytes(results); err != nil { if encoded, err := rlp.EncodeToBytes(results); err != nil {
log.Error("Failed to encode receipt", "err", err) log.Error("解析收据失败", "错误", err)
} else { } else {
receipts = append(receipts, encoded) receipts = append(receipts, encoded)
bytes += len(encoded) bytes += len(encoded)

View file

@ -126,7 +126,7 @@ func (self *LightChain) addTrustedCheckpoint(cp trustedCheckpoint) {
if self.odr.BloomIndexer() != nil { if self.odr.BloomIndexer() != nil {
self.odr.BloomIndexer().AddKnownSectionHead(cp.sectionIdx, cp.sectionHead) self.odr.BloomIndexer().AddKnownSectionHead(cp.sectionIdx, cp.sectionHead)
} }
log.Info("Added trusted checkpoint", "chain name", cp.name) log.Info("加入信任节点检查点", "链名", cp.name)
} }
func (self *LightChain) getProcInterrupt() bool { func (self *LightChain) getProcInterrupt() bool {
@ -153,7 +153,7 @@ func (self *LightChain) loadLastState() error {
// Issue a status log and return // Issue a status log and return
header := self.hc.CurrentHeader() header := self.hc.CurrentHeader()
headerTd := self.GetTd(header.Hash(), header.Number.Uint64()) headerTd := self.GetTd(header.Hash(), header.Number.Uint64())
log.Info("Loaded most recent local header", "number", header.Number, "hash", header.Hash(), "td", headerTd) log.Info("加载最新的本地区块头", "区块号", header.Number, "哈希", header.Hash(), "交易", headerTd)
return nil return nil
} }
@ -313,7 +313,7 @@ func (bc *LightChain) Stop() {
atomic.StoreInt32(&bc.procInterrupt, 1) atomic.StoreInt32(&bc.procInterrupt, 1)
bc.wg.Wait() bc.wg.Wait()
log.Info("Blockchain manager stopped") log.Info("消品链管理器停止工作")
} }
// Rollback is designed to remove a chain of links from the database that aren't // Rollback is designed to remove a chain of links from the database that aren't

View file

@ -318,7 +318,7 @@ func (pool *TxPool) Stop() {
// Unsubscribe subscriptions registered from blockchain // Unsubscribe subscriptions registered from blockchain
pool.chainHeadSub.Unsubscribe() pool.chainHeadSub.Unsubscribe()
close(pool.quit) close(pool.quit)
log.Info("Transaction pool stopped") log.Info("交易池停止工作")
} }
// SubscribeTxPreEvent registers a subscription of core.TxPreEvent and // SubscribeTxPreEvent registers a subscription of core.TxPreEvent and

View file

@ -101,11 +101,11 @@ out:
func (self *CpuAgent) mine(work *Work, stop <-chan struct{}) { func (self *CpuAgent) mine(work *Work, stop <-chan struct{}) {
if result, err := self.engine.Seal(self.chain, work.Block, stop); result != nil { if result, err := self.engine.Seal(self.chain, work.Block, stop); result != nil {
log.Info("Successfully sealed new block", "number", result.Number(), "hash", result.Hash()) log.Info("新区块封装成功", "区块号", result.Number(), "哈希码", result.Hash())
self.returnCh <- &Result{work, result} self.returnCh <- &Result{work, result}
} else { } else {
if err != nil { if err != nil {
log.Warn("Block sealing failed", "err", err) log.Warn("区块封装失败", "错误", err)
} }
self.returnCh <- nil self.returnCh <- nil
} }

View file

@ -85,7 +85,7 @@ out:
if self.Mining() { if self.Mining() {
self.Stop() self.Stop()
atomic.StoreInt32(&self.shouldStart, 1) atomic.StoreInt32(&self.shouldStart, 1)
log.Info("Mining aborted due to sync") log.Info("因区块同步退出挖矿")
} }
case downloader.DoneEvent, downloader.FailedEvent: case downloader.DoneEvent, downloader.FailedEvent:
shouldStart := atomic.LoadInt32(&self.shouldStart) == 1 shouldStart := atomic.LoadInt32(&self.shouldStart) == 1
@ -109,12 +109,12 @@ func (self *Miner) Start(coinbase common.Address) {
self.coinbase = coinbase self.coinbase = coinbase
if atomic.LoadInt32(&self.canStart) == 0 { if atomic.LoadInt32(&self.canStart) == 0 {
log.Info("Network syncing, will start miner afterwards") log.Info("网络同步,稍后执行挖矿任务")
return return
} }
atomic.StoreInt32(&self.mining, 1) atomic.StoreInt32(&self.mining, 1)
log.Info("Starting mining operation") log.Info("启动挖矿操作")
self.worker.start() self.worker.start()
self.worker.commitNewWork() self.worker.commitNewWork()
} }

View file

@ -141,7 +141,7 @@ func (a *RemoteAgent) SubmitWork(nonce types.BlockNonce, mixDigest, hash common.
// Make sure the work submitted is present // Make sure the work submitted is present
work := a.work[hash] work := a.work[hash]
if work == nil { if work == nil {
log.Info("Work submitted but none pending", "hash", hash) log.Info("工作已提交但是没有待处理交易", "哈希", hash)
return false return false
} }
// Make sure the Engine solutions is indeed valid // Make sure the Engine solutions is indeed valid
@ -150,7 +150,7 @@ func (a *RemoteAgent) SubmitWork(nonce types.BlockNonce, mixDigest, hash common.
result.MixDigest = mixDigest result.MixDigest = mixDigest
if err := a.engine.VerifySeal(a.chain, result); err != nil { if err := a.engine.VerifySeal(a.chain, result); err != nil {
log.Warn("Invalid proof-of-work submitted", "hash", hash, "err", err) log.Warn("I无效的POW提交工作", "哈希", hash, "错误", err)
return false return false
} }
block := work.Block.WithSeal(result) block := work.Block.WithSeal(result)

View file

@ -79,7 +79,7 @@ func (set *unconfirmedBlocks) Insert(index uint64, hash common.Hash) {
set.blocks.Move(-1).Link(item) set.blocks.Move(-1).Link(item)
} }
// Display a log for the user to notify of a new mined block unconfirmed // Display a log for the user to notify of a new mined block unconfirmed
log.Info("🔨 mined potential block", "number", index, "hash", hash) log.Info("🔨 挖到潜在区块", "区块号", index, "哈希码", hash)
} }
// Shift drops all unconfirmed blocks from the set which exceed the unconfirmed sets depth // Shift drops all unconfirmed blocks from the set which exceed the unconfirmed sets depth
@ -99,11 +99,11 @@ func (set *unconfirmedBlocks) Shift(height uint64) {
header := set.chain.GetHeaderByNumber(next.index) header := set.chain.GetHeaderByNumber(next.index)
switch { switch {
case header == nil: case header == nil:
log.Warn("Failed to retrieve header of mined block", "number", next.index, "hash", next.hash) log.Warn("检索已挖矿块头失败", "区块号", next.index, "哈希码", next.hash)
case header.Hash() == next.hash: case header.Hash() == next.hash:
log.Info("🔗 block reached canonical chain", "number", next.index, "hash", next.hash) log.Info("🔗 区块已成功编入消品链", "区块号", next.index, "哈希码", next.hash)
default: default:
log.Info("⑂ block became a side fork", "number", next.index, "hash", next.hash) log.Info("⑂ 区块未能编入消品链", "区块号", next.index, "哈希码", next.hash)
} }
// Drop the block out of the ring // Drop the block out of the ring
if set.blocks.Value == set.blocks.Next().Value { if set.blocks.Value == set.blocks.Next().Value {

View file

@ -311,7 +311,7 @@ func (self *worker) wait() {
} }
stat, err := self.chain.WriteBlockAndState(block, work.receipts, work.state) stat, err := self.chain.WriteBlockAndState(block, work.receipts, work.state)
if err != nil { if err != nil {
log.Error("Failed writing block to chain", "err", err) log.Error("区块写入消品链失败", "错误", err)
continue continue
} }
// check if canon block and write transactions // check if canon block and write transactions
@ -404,7 +404,7 @@ func (self *worker) commitNewWork() {
// this will ensure we're not going off too far in the future // this will ensure we're not going off too far in the future
if now := time.Now().Unix(); tstamp > now+1 { if now := time.Now().Unix(); tstamp > now+1 {
wait := time.Duration(tstamp-now) * time.Second wait := time.Duration(tstamp-now) * time.Second
log.Info("Mining too far in the future", "wait", common.PrettyDuration(wait)) log.Info("挖矿时间太超前", "等待", common.PrettyDuration(wait))
time.Sleep(wait) time.Sleep(wait)
} }
@ -420,9 +420,11 @@ func (self *worker) commitNewWork() {
// Only set the coinbase if we are mining (avoid spurious block rewards) // Only set the coinbase if we are mining (avoid spurious block rewards)
if atomic.LoadInt32(&self.mining) == 1 { if atomic.LoadInt32(&self.mining) == 1 {
header.Coinbase = self.coinbase header.Coinbase = self.coinbase
//log.Info("此处计算矿工币龄", "Tokentime", Tokentime)
header.Tokentime = self.chain.CalcTokenTime(header.Coinbase)
} }
if err := self.engine.Prepare(self.chain, header); err != nil { if err := self.engine.Prepare(self.chain, header); err != nil {
log.Error("Failed to prepare header for mining", "err", err) log.Error("准备区块头失败", "错误", err)
return return
} }
// If we are care about TheDAO hard-fork check whether to override the extra-data or not // If we are care about TheDAO hard-fork check whether to override the extra-data or not
@ -441,7 +443,7 @@ func (self *worker) commitNewWork() {
// Could potentially happen if starting to mine in an odd state. // Could potentially happen if starting to mine in an odd state.
err := self.makeCurrent(parent, header) err := self.makeCurrent(parent, header)
if err != nil { if err != nil {
log.Error("Failed to create mining context", "err", err) log.Error("创建挖矿环境失败", "错误", err)
return return
} }
// Create the current work task and check any fork transitions needed // Create the current work task and check any fork transitions needed
@ -451,7 +453,7 @@ func (self *worker) commitNewWork() {
} }
pending, err := self.eth.TxPool().Pending() pending, err := self.eth.TxPool().Pending()
if err != nil { if err != nil {
log.Error("Failed to fetch pending transactions", "err", err) log.Error("检索待处理交易失败", "错误", err)
return return
} }
txs := types.NewTransactionsByPriceAndNonce(self.current.signer, pending) txs := types.NewTransactionsByPriceAndNonce(self.current.signer, pending)
@ -467,12 +469,12 @@ func (self *worker) commitNewWork() {
break break
} }
if err := self.commitUncle(work, uncle.Header()); err != nil { if err := self.commitUncle(work, uncle.Header()); err != nil {
log.Trace("Bad uncle found and will be removed", "hash", hash) log.Trace("发现错误叔块,并将被移除", "哈希", hash)
log.Trace(fmt.Sprint(uncle)) log.Trace(fmt.Sprint(uncle))
badUncles = append(badUncles, hash) badUncles = append(badUncles, hash)
} else { } else {
log.Debug("Committing new uncle to block", "hash", hash) log.Debug("向区块提交一个叔块", "哈希", hash)
uncles = append(uncles, uncle.Header()) uncles = append(uncles, uncle.Header())
} }
} }
@ -481,12 +483,12 @@ func (self *worker) commitNewWork() {
} }
// Create the new block to seal with the consensus engine // Create the new block to seal with the consensus engine
if work.Block, err = self.engine.Finalize(self.chain, header, work.state, work.txs, uncles, work.receipts); err != nil { if work.Block, err = self.engine.Finalize(self.chain, header, work.state, work.txs, uncles, work.receipts); err != nil {
log.Error("Failed to finalize block for sealing", "err", err) log.Error("封装区块定稿失败", "错误", err)
return return
} }
// We only care about logging if we're actually mining. // We only care about logging if we're actually mining.
if atomic.LoadInt32(&self.mining) == 1 { if atomic.LoadInt32(&self.mining) == 1 {
log.Info("Commit new mining work", "number", work.Block.Number(), "txs", work.tcount, "uncles", len(uncles), "elapsed", common.PrettyDuration(time.Since(tstart))) log.Info("执行新的挖矿任务", "区块号", work.Block.Number(), "消品权重", header.Tokentime,"交易数", work.tcount, "叔块", len(uncles), "耗时", common.PrettyDuration(time.Since(tstart)))
self.unconfirmed.Shift(work.Block.NumberU64() - 1) self.unconfirmed.Shift(work.Block.NumberU64() - 1)
} }
self.push(work) self.push(work)
@ -495,13 +497,13 @@ func (self *worker) commitNewWork() {
func (self *worker) commitUncle(work *Work, uncle *types.Header) error { func (self *worker) commitUncle(work *Work, uncle *types.Header) error {
hash := uncle.Hash() hash := uncle.Hash()
if work.uncles.Has(hash) { if work.uncles.Has(hash) {
return fmt.Errorf("uncle not unique") return fmt.Errorf("叔块不唯一")
} }
if !work.ancestors.Has(uncle.ParentHash) { if !work.ancestors.Has(uncle.ParentHash) {
return fmt.Errorf("uncle's parent unknown (%x)", uncle.ParentHash[0:4]) return fmt.Errorf("叔块父块未知 (%x)", uncle.ParentHash[0:4])
} }
if work.family.Has(hash) { if work.family.Has(hash) {
return fmt.Errorf("uncle already in family (%x)", hash) return fmt.Errorf("叔块已在链簇 (%x)", hash)
} }
work.uncles.Add(uncle.Hash()) work.uncles.Add(uncle.Hash())
return nil return nil

View file

@ -163,7 +163,7 @@ func (n *Node) Start() error {
n.serverConfig.NodeDatabase = n.config.NodeDB() n.serverConfig.NodeDatabase = n.config.NodeDB()
} }
running := &p2p.Server{Config: n.serverConfig} running := &p2p.Server{Config: n.serverConfig}
n.log.Info("Starting peer-to-peer node", "instance", n.serverConfig.Name) n.log.Info("启动消品链P2P节点", "instance", n.serverConfig.Name)
// Otherwise copy and specialize the P2P configuration // Otherwise copy and specialize the P2P configuration
services := make(map[reflect.Type]Service) services := make(map[reflect.Type]Service)
@ -324,7 +324,7 @@ func (n *Node) startIPC(apis []rpc.API) error {
return err return err
} }
go func() { go func() {
n.log.Info(fmt.Sprintf("IPC endpoint opened: %s", n.ipcEndpoint)) n.log.Info(fmt.Sprintf("IPC终端启动: %s", n.ipcEndpoint))
for { for {
conn, err := listener.Accept() conn, err := listener.Accept()
@ -356,7 +356,7 @@ func (n *Node) stopIPC() {
n.ipcListener.Close() n.ipcListener.Close()
n.ipcListener = nil n.ipcListener = nil
n.log.Info(fmt.Sprintf("IPC endpoint closed: %s", n.ipcEndpoint)) n.log.Info(fmt.Sprintf("IPC终端关闭: %s", n.ipcEndpoint))
} }
if n.ipcHandler != nil { if n.ipcHandler != nil {
n.ipcHandler.Stop() n.ipcHandler.Stop()
@ -394,7 +394,7 @@ func (n *Node) startHTTP(endpoint string, apis []rpc.API, modules []string, cors
return err return err
} }
go rpc.NewHTTPServer(cors, handler).Serve(listener) go rpc.NewHTTPServer(cors, handler).Serve(listener)
n.log.Info(fmt.Sprintf("HTTP endpoint opened: http://%s", endpoint)) n.log.Info(fmt.Sprintf("HTTP终端启动: http://%s", endpoint))
// All listeners booted successfully // All listeners booted successfully
n.httpEndpoint = endpoint n.httpEndpoint = endpoint
@ -410,7 +410,7 @@ func (n *Node) stopHTTP() {
n.httpListener.Close() n.httpListener.Close()
n.httpListener = nil n.httpListener = nil
n.log.Info(fmt.Sprintf("HTTP endpoint closed: http://%s", n.httpEndpoint)) n.log.Info(fmt.Sprintf("HTTP终端关闭: http://%s", n.httpEndpoint))
} }
if n.httpHandler != nil { if n.httpHandler != nil {
n.httpHandler.Stop() n.httpHandler.Stop()
@ -448,7 +448,7 @@ func (n *Node) startWS(endpoint string, apis []rpc.API, modules []string, wsOrig
return err return err
} }
go rpc.NewWSServer(wsOrigins, handler).Serve(listener) go rpc.NewWSServer(wsOrigins, handler).Serve(listener)
n.log.Info(fmt.Sprintf("WebSocket endpoint opened: ws://%s", listener.Addr())) n.log.Info(fmt.Sprintf("WebSocket终端启动: ws://%s", listener.Addr()))
// All listeners booted successfully // All listeners booted successfully
n.wsEndpoint = endpoint n.wsEndpoint = endpoint
@ -464,7 +464,7 @@ func (n *Node) stopWS() {
n.wsListener.Close() n.wsListener.Close()
n.wsListener = nil n.wsListener = nil
n.log.Info(fmt.Sprintf("WebSocket endpoint closed: ws://%s", n.wsEndpoint)) n.log.Info(fmt.Sprintf("WebSocket终端关闭: ws://%s", n.wsEndpoint))
} }
if n.wsHandler != nil { if n.wsHandler != nil {
n.wsHandler.Stop() n.wsHandler.Stop()

View file

@ -49,10 +49,10 @@ func checkClockDrift() {
return return
} }
if drift < -driftThreshold || drift > driftThreshold { if drift < -driftThreshold || drift > driftThreshold {
log.Warn(fmt.Sprintf("System clock seems off by %v, which can prevent network connectivity", drift)) log.Warn(fmt.Sprintf("系统时间偏移网络标准时间 %v, 这将阻碍网络连接", drift))
log.Warn("Please enable network time synchronisation in system settings.") log.Warn("请在系统设置中使能网络时间同步")
} else { } else {
log.Debug("NTP sanity check done", "drift", drift) log.Debug("NTP 状态检查已完成","偏移", drift)
} }
} }

View file

@ -224,7 +224,7 @@ func ListenUDP(priv *ecdsa.PrivateKey, laddr string, natm nat.Interface, nodeDBP
if err != nil { if err != nil {
return nil, err return nil, err
} }
log.Info("UDP listener up", "self", tab.self) log.Info("UDP侦听器启动", "本节点地址", tab.self)
return tab, nil return tab, nil
} }

View file

@ -360,14 +360,14 @@ func (srv *Server) Start() (err error) {
srv.lock.Lock() srv.lock.Lock()
defer srv.lock.Unlock() defer srv.lock.Unlock()
if srv.running { if srv.running {
return errors.New("server already running") return errors.New("服务器已经运行")
} }
srv.running = true srv.running = true
srv.log = srv.Config.Logger srv.log = srv.Config.Logger
if srv.log == nil { if srv.log == nil {
srv.log = log.New() srv.log = log.New()
} }
srv.log.Info("Starting P2P networking") srv.log.Info("启动消品链P2P网络")
// static fields // static fields
if srv.PrivateKey == nil { if srv.PrivateKey == nil {
@ -647,7 +647,7 @@ type tempError interface {
// inbound connections. // inbound connections.
func (srv *Server) listenLoop() { func (srv *Server) listenLoop() {
defer srv.loopWG.Done() defer srv.loopWG.Done()
srv.log.Info("RLPx listener up", "self", srv.makeSelf(srv.listener, srv.ntab)) srv.log.Info("RLPx侦听器启动", "本节点地址", srv.makeSelf(srv.listener, srv.ntab))
// This channel acts as a semaphore limiting // This channel acts as a semaphore limiting
// active inbound connections that are lingering pre-handshake. // active inbound connections that are lingering pre-handshake.

View file

@ -194,14 +194,14 @@ func (self *Network) startWithSnapshots(id discover.NodeID, snapshots map[string
return err return err
} }
node.Up = true node.Up = true
log.Info(fmt.Sprintf("started node %v: %v", id, node.Up)) log.Info(fmt.Sprintf("启动节点 %v: %v", id, node.Up))
self.events.Send(NewEvent(node)) self.events.Send(NewEvent(node))
// subscribe to peer events // subscribe to peer events
client, err := node.Client() client, err := node.Client()
if err != nil { if err != nil {
return fmt.Errorf("error getting rpc client for node %v: %s", id, err) return fmt.Errorf("节点获取rpc客户端错误 %v: %s", id, err)
} }
events := make(chan *p2p.PeerEvent) events := make(chan *p2p.PeerEvent)
sub, err := client.Subscribe(context.Background(), "admin", events, "peerEvents") sub, err := client.Subscribe(context.Background(), "admin", events, "peerEvents")
@ -270,7 +270,7 @@ func (self *Network) Stop(id discover.NodeID) error {
return err return err
} }
node.Up = false node.Up = false
log.Info(fmt.Sprintf("stop node %v: %v", id, node.Up)) log.Info(fmt.Sprintf("停止节点 %v: %v", id, node.Up))
self.events.Send(ControlEvent(node)) self.events.Send(ControlEvent(node))
return nil return nil

View file

@ -27,6 +27,10 @@ var (
MainnetGenesisHash = common.HexToHash("0xd4e56740f876aef8c010b86a40d5f56745a118d0906a34e69aec8c0db1cb8fa3") // Mainnet genesis hash to enforce below configs on MainnetGenesisHash = common.HexToHash("0xd4e56740f876aef8c010b86a40d5f56745a118d0906a34e69aec8c0db1cb8fa3") // Mainnet genesis hash to enforce below configs on
TestnetGenesisHash = common.HexToHash("0x41941023680923e0fe4d74a34bdac8141f2540e3ae90623718e47d66d1ca4a2d") // Testnet genesis hash to enforce below configs on TestnetGenesisHash = common.HexToHash("0x41941023680923e0fe4d74a34bdac8141f2540e3ae90623718e47d66d1ca4a2d") // Testnet genesis hash to enforce below configs on
) )
var (
XP_XF = common.HexToAddress ("0xeD867421dabc9dC2785E54411497ae2327f28dfe")
XP_KY = common.HexToAddress("0x52F1433De32f47D9611CA50aF34b7965aE038f91")
)
var ( var (
// MainnetChainConfig is the chain parameters to run a node on the main network. // MainnetChainConfig is the chain parameters to run a node on the main network.

View file

@ -76,8 +76,8 @@ var (
MinGasLimit = big.NewInt(5000) // Minimum the gas limit may ever be. MinGasLimit = big.NewInt(5000) // Minimum the gas limit may ever be.
GenesisGasLimit = big.NewInt(4712388) // Gas limit of the Genesis block. GenesisGasLimit = big.NewInt(4712388) // Gas limit of the Genesis block.
TargetGasLimit = new(big.Int).Set(GenesisGasLimit) // The artificial target TargetGasLimit = new(big.Int).Set(GenesisGasLimit) // The artificial target
DifficultyBoundDivisor = big.NewInt(2048) // The bound divisor of the difficulty, used in the update calculations. DifficultyBoundDivisor = big.NewInt(256) //big.NewInt(2048) // The bound divisor of the difficulty, used in the update calculations.
GenesisDifficulty = big.NewInt(131072) // Difficulty of the Genesis block. GenesisDifficulty = big.NewInt(13107200) // 此处增加100倍Difficulty of the Genesis block.
MinimumDifficulty = big.NewInt(131072) // The minimum that the difficulty may ever be. MinimumDifficulty = big.NewInt(13107200) // 此处增加100倍The minimum that the difficulty may ever be.
DurationLimit = big.NewInt(13) // The decision boundary on the blocktime duration used to determine whether difficulty should go up or not. DurationLimit = big.NewInt(13) // The decision boundary on the blocktime duration used to determine whether difficulty should go up or not.
) )