主頁 > 後端開發 > ETH開發(二)搭建基于go-ethereum的以太坊的私有鏈環境

ETH開發(二)搭建基于go-ethereum的以太坊的私有鏈環境

2020-09-13 07:45:17 後端開發

上篇文章,我們編譯了go-ethereum的源代碼,大家體驗了一下開發環境,使用了開發工具,我們從這章開始,進入ETH的學習階段,我會在每章完成后,給大家提出一些思考,幫助大家,
1、搭建前準備

如果是使用虛擬機上安裝的 Ubuntu,請在虛擬機中打開終端,安裝SSH,

命令如下:

sudo apt-get install ssh

Windows上,安裝 SSH終端工具MobaXterm Professional Edition,自己安裝,MAC系統,自帶遠程工具,或者選擇自己喜歡的遠程工具如putty或者其他,
編輯器 Visual Studio Code ,可以安裝在windows環境下或者MAC下,如果想通過Visual Studio Code操作ubuntu下的檔案,請在Visual Studio Code安裝拓展插件,
點擊左側狀態欄”擴展“ 輸入 Remote Development 點擊安裝,安裝后,會有檔案,詳細介紹如何連接遠程主機,及操作檔案,如下圖:
在這里插入圖片描述

Ubuntu下安裝命令
上篇文章,我們通過編譯源代碼的方式,自己編譯了geth客戶端,如果僅僅是使用ETH網路,我們可以只安裝ETH客戶端即可,根據自己場景需要決定,
命令如下:

sudo apt-get install software-properties-common
sudo add-apt-repository -y ppa:ethereum/ethereum
sudo add-apt-repository -y ppa:ethereum/ethereum-dev
sudo apt-get update
sudo apt-get install ethereum

安裝測驗
安裝好后,我們輸入如下命令:

geth -h 

顯示如下:

NAME:
   geth - the go-ethereum command line interface

   Copyright 2013-2019 The go-ethereum Authors

USAGE:
   geth [options] command [command options] [arguments...]

VERSION:
   1.9.19-stable-3e064192

COMMANDS:
   account                            Manage accounts
   attach                             Start an interactive JavaScript environment (connect to node)
   console                            Start an interactive JavaScript environment
   copydb                             Create a local chain from a target chaindata folder
   dump                               Dump a specific block from storage
   dumpconfig                         Show configuration values
   dumpgenesis                        Dumps genesis block JSON configuration to stdout
   export                             Export blockchain into file
   export-preimages                   Export the preimage database into an RLP stream
   import                             Import a blockchain file
   import-preimages                   Import the preimage database from an RLP stream
   init                               Bootstrap and initialize a new genesis block
   inspect                            Inspect the storage size for each type of data in the database
   js                                 Execute the specified JavaScript files
   license                            Display license information
   makecache                          Generate ethash verification cache (for testing)
   makedag                            Generate ethash mining DAG (for testing)
   removedb                           Remove blockchain and state databases
   retesteth                          Launches geth in retesteth mode
   show-deprecated-flags              Show flags that have been deprecated
   version                            Print version numbers
   wallet                             Manage Ethereum presale wallets
   help, h                            Shows a list of commands or help for one command

ETHEREUM OPTIONS:
  --config value                      TOML configuration file
  --datadir value                     Data directory for the databases and keystore (default: "/home/cuijb/.ethereum")
  --datadir.ancient value             Data directory for ancient chain segments (default = inside chaindata)
  --keystore value                    Directory for the keystore (default = inside the datadir)
  --nousb                             Disables monitoring for and managing USB hardware wallets
  --pcscdpath value                   Path to the smartcard daemon (pcscd) socket file (default: "/run/pcscd/pcscd.comm")
  --networkid value                   Network identifier (integer, 1=Frontier, 3=Ropsten, 4=Rinkeby, 5=G?rli) (default: 1)
  --goerli                            G?rli network: pre-configured proof-of-authority test network
  --rinkeby                           Rinkeby network: pre-configured proof-of-authority test network
  --yolov1                            YOLOv1 network: pre-configured proof-of-authority shortlived test network.
  --ropsten                           Ropsten network: pre-configured proof-of-work test network
  --syncmode value                    Blockchain sync mode ("fast", "full", or "light") (default: fast)
  --exitwhensynced                    Exits after block synchronisation completes
  --gcmode value                      Blockchain garbage collection mode ("full", "archive") (default: "full")
  --txlookuplimit value               Number of recent blocks to maintain transactions index by-hash for (default = index all blocks) (default: 0)
  --ethstats value                    Reporting URL of a ethstats service (nodename:secret@host:port)
  --identity value                    Custom node name
  --lightkdf                          Reduce key-derivation RAM & CPU usage at some expense of KDF strength
  --whitelist value                   Comma separated block number-to-hash mappings to enforce (<number>=<hash>)

LIGHT CLIENT OPTIONS:
  --light.serve value                 Maximum percentage of time allowed for serving LES requests (multi-threaded processing allows values over 100) (default: 0)
  --light.ingress value               Incoming bandwidth limit for serving light clients (kilobytes/sec, 0 = unlimited) (default: 0)
  --light.egress value                Outgoing bandwidth limit for serving light clients (kilobytes/sec, 0 = unlimited) (default: 0)
  --light.maxpeers value              Maximum number of light clients to serve, or light servers to attach to (default: 100)
  --ulc.servers value                 List of trusted ultra-light servers
  --ulc.fraction value                Minimum % of trusted ultra-light servers required to announce a new head (default: 75)
  --ulc.onlyannounce                  Ultra light server sends announcements only
  --light.nopruning                   Disable ancient light chain data pruning

DEVELOPER CHAIN OPTIONS:
  --dev                               Ephemeral proof-of-authority network with a pre-funded developer account, mining enabled
  --dev.period value                  Block period to use in developer mode (0 = mine only if transaction pending) (default: 0)

ETHASH OPTIONS:
  --ethash.cachedir value             Directory to store the ethash verification caches (default = inside the datadir)
  --ethash.cachesinmem value          Number of recent ethash caches to keep in memory (16MB each) (default: 2)
  --ethash.cachesondisk value         Number of recent ethash caches to keep on disk (16MB each) (default: 3)
  --ethash.cacheslockmmap             Lock memory maps of recent ethash caches
  --ethash.dagdir value               Directory to store the ethash mining DAGs (default: "/home/cuijb/.ethash")
  --ethash.dagsinmem value            Number of recent ethash mining DAGs to keep in memory (1+GB each) (default: 1)
  --ethash.dagsondisk value           Number of recent ethash mining DAGs to keep on disk (1+GB each) (default: 2)
  --ethash.dagslockmmap               Lock memory maps for recent ethash mining DAGs

TRANSACTION POOL OPTIONS:
  --txpool.locals value               Comma separated accounts to treat as locals (no flush, priority inclusion)
  --txpool.nolocals                   Disables price exemptions for locally submitted transactions
  --txpool.journal value              Disk journal for local transaction to survive node restarts (default: "transactions.rlp")
  --txpool.rejournal value            Time interval to regenerate the local transaction journal (default: 1h0m0s)
  --txpool.pricelimit value           Minimum gas price limit to enforce for acceptance into the pool (default: 1)
  --txpool.pricebump value            Price bump percentage to replace an already existing transaction (default: 10)
  --txpool.accountslots value         Minimum number of executable transaction slots guaranteed per account (default: 16)
  --txpool.globalslots value          Maximum number of executable transaction slots for all accounts (default: 4096)
  --txpool.accountqueue value         Maximum number of non-executable transaction slots permitted per account (default: 64)
  --txpool.globalqueue value          Maximum number of non-executable transaction slots for all accounts (default: 1024)
  --txpool.lifetime value             Maximum amount of time non-executable transaction are queued (default: 3h0m0s)

PERFORMANCE TUNING OPTIONS:
  --cache value                       Megabytes of memory allocated to internal caching (default = 4096 mainnet full node, 128 light mode) (default: 1024)
  --cache.database value              Percentage of cache memory allowance to use for database io (default: 50)
  --cache.trie value                  Percentage of cache memory allowance to use for trie caching (default = 15% full mode, 30% archive mode) (default: 15)
  --cache.trie.journal value          Disk journal directory for trie cache to survive node restarts (default: "triecache")
  --cache.trie.rejournal value        Time interval to regenerate the trie cache journal (default: 1h0m0s)
  --cache.gc value                    Percentage of cache memory allowance to use for trie pruning (default = 25% full mode, 0% archive mode) (default: 25)
  --cache.snapshot value              Percentage of cache memory allowance to use for snapshot caching (default = 10% full mode, 20% archive mode) (default: 10)
  --cache.noprefetch                  Disable heuristic state prefetch during block import (less CPU and disk IO, more time waiting for data)

ACCOUNT OPTIONS:
  --unlock value                      Comma separated list of accounts to unlock
  --password value                    Password file to use for non-interactive password input
  --signer value                      External signer (url or path to ipc file)
  --allow-insecure-unlock             Allow insecure account unlocking when account-related RPCs are exposed by http

API AND CONSOLE OPTIONS:
  --ipcdisable                        Disable the IPC-RPC server
  --ipcpath value                     Filename for IPC socket/pipe within the datadir (explicit paths escape it)
  --http                              Enable the HTTP-RPC server
  --http.addr value                   HTTP-RPC server listening interface (default: "localhost")
  --http.port value                   HTTP-RPC server listening port (default: 8545)
  --http.api value                    API's offered over the HTTP-RPC interface
  --http.corsdomain value             Comma separated list of domains from which to accept cross origin requests (browser enforced)
  --http.vhosts value                 Comma separated list of virtual hostnames from which to accept requests (server enforced). Accepts '*' wildcard. (default: "localhost")
  --ws                                Enable the WS-RPC server
  --ws.addr value                     WS-RPC server listening interface (default: "localhost")
  --ws.port value                     WS-RPC server listening port (default: 8546)
  --ws.api value                      API's offered over the WS-RPC interface
  --ws.origins value                  Origins from which to accept websockets requests
  --graphql                           Enable GraphQL on the HTTP-RPC server. Note that GraphQL can only be started if an HTTP server is started as well.
  --graphql.corsdomain value          Comma separated list of domains from which to accept cross origin requests (browser enforced)
  --graphql.vhosts value              Comma separated list of virtual hostnames from which to accept requests (server enforced). Accepts '*' wildcard. (default: "localhost")
  --rpc.gascap value                  Sets a cap on gas that can be used in eth_call/estimateGas (0=infinite) (default: 25000000)
  --rpc.txfeecap value                Sets a cap on transaction fee (in ether) that can be sent via the RPC APIs (0 = no cap) (default: 1)
  --jspath loadScript                 JavaScript root path for loadScript (default: ".")
  --exec value                        Execute JavaScript statement
  --preload value                     Comma separated list of JavaScript files to preload into the console

NETWORKING OPTIONS:
  --bootnodes value                   Comma separated enode URLs for P2P discovery bootstrap
  --bootnodesv4 value                 Comma separated enode URLs for P2P v4 discovery bootstrap (light server, full nodes) (deprecated, use --bootnodes)
  --bootnodesv5 value                 Comma separated enode URLs for P2P v5 discovery bootstrap (light server, light nodes) (deprecated, use --bootnodes)
  --discovery.dns value               Sets DNS discovery entry points (use "" to disable DNS)
  --port value                        Network listening port (default: 30303)
  --maxpeers value                    Maximum number of network peers (network disabled if set to 0) (default: 50)
  --maxpendpeers value                Maximum number of pending connection attempts (defaults used if set to 0) (default: 0)
  --nat value                         NAT port mapping mechanism (any|none|upnp|pmp|extip:<IP>) (default: "any")
  --nodiscover                        Disables the peer discovery mechanism (manual peer addition)
  --v5disc                            Enables the experimental RLPx V5 (Topic Discovery) mechanism
  --netrestrict value                 Restricts network communication to the given IP networks (CIDR masks)
  --nodekey value                     P2P node key file
  --nodekeyhex value                  P2P node key as hex (for testing)

MINER OPTIONS:
  --mine                              Enable mining
  --miner.threads value               Number of CPU threads to use for mining (default: 0)
  --miner.notify value                Comma separated HTTP URL list to notify of new work packages
  --miner.gasprice value              Minimum gas price for mining a transaction (default: 1000000000)
  --miner.gastarget value             Target gas floor for mined blocks (default: 8000000)
  --miner.gaslimit value              Target gas ceiling for mined blocks (default: 8000000)
  --miner.etherbase value             Public address for block mining rewards (default = first account) (default: "0")
  --miner.extradata value             Block extra data set by the miner (default = client version)
  --miner.recommit value              Time interval to recreate the block being mined (default: 3s)
  --miner.noverify                    Disable remote sealing verification

GAS PRICE ORACLE OPTIONS:
  --gpo.blocks value                  Number of recent blocks to check for gas prices (default: 20)
  --gpo.percentile value              Suggested gas price is the given percentile of a set of recent transaction gas prices (default: 60)

VIRTUAL MACHINE OPTIONS:
  --vmdebug                           Record information useful for VM and contract debugging
  --vm.evm value                      External EVM configuration (default = built-in interpreter)
  --vm.ewasm value                    External ewasm configuration (default = built-in interpreter)

LOGGING AND DEBUGGING OPTIONS:
  --fakepow                           Disables proof-of-work verification
  --nocompaction                      Disables db compaction after import
  --verbosity value                   Logging verbosity: 0=silent, 1=error, 2=warn, 3=info, 4=debug, 5=detail (default: 3)
  --vmodule value                     Per-module verbosity: comma-separated list of <pattern>=<level> (e.g. eth/*=5,p2p=4)
  --backtrace value                   Request a stack trace at a specific logging statement (e.g. "block.go:271")
  --debug                             Prepends log messages with call-site location (file and line number)
  --pprof                             Enable the pprof HTTP server
  --pprof.addr value                  pprof HTTP server listening interface (default: "127.0.0.1")
  --pprof.port value                  pprof HTTP server listening port (default: 6060)
  --pprof.memprofilerate value        Turn on memory profiling with the given rate (default: 524288)
  --pprof.blockprofilerate value      Turn on block profiling with the given rate (default: 0)
  --pprof.cpuprofile value            Write CPU profile to the given file
  --trace value                       Write execution trace to the given file

METRICS AND STATS OPTIONS:
  --metrics                           Enable metrics collection and reporting
  --metrics.expensive                 Enable expensive metrics collection and reporting
  --metrics.addr value                Enable stand-alone metrics HTTP server listening interface (default: "127.0.0.1")
  --metrics.port value                Metrics HTTP server listening port (default: 6060)
  --metrics.influxdb                  Enable metrics export/push to an external InfluxDB database
  --metrics.influxdb.endpoint value   InfluxDB API endpoint to report metrics to (default: "http://localhost:8086")
  --metrics.influxdb.database value   InfluxDB database name to push reported metrics to (default: "geth")
  --metrics.influxdb.username value   Username to authorize access to the database (default: "test")
  --metrics.influxdb.password value   Password to authorize access to the database (default: "test")
  --metrics.influxdb.tags value       Comma-separated InfluxDB tags (key/values) attached to all measurements (default: "host=localhost")

WHISPER (EXPERIMENTAL) OPTIONS:
  --shh                               Enable Whisper
  --shh.maxmessagesize value          Max message size accepted (default: 1048576)
  --shh.pow value                     Minimum POW accepted (default: 0.2)
  --shh.restrict-light                Restrict connection between two whisper light clients

ALIASED (deprecated) OPTIONS:
  --rpc                               Enable the HTTP-RPC server (deprecated, use --http)
  --rpcaddr value                     HTTP-RPC server listening interface (deprecated, use --http.addr) (default: "localhost")
  --rpcport value                     HTTP-RPC server listening port (deprecated, use --http.port) (default: 8545)
  --rpccorsdomain value               Comma separated list of domains from which to accept cross origin requests (browser enforced) (deprecated, use --http.corsdomain)
  --rpcvhosts value                   Comma separated list of virtual hostnames from which to accept requests (server enforced). Accepts '*' wildcard. (deprecated, use --http.vhosts) (default: "localhost")
  --rpcapi value                      API's offered over the HTTP-RPC interface (deprecated, use --http.api)
  --wsaddr value                      WS-RPC server listening interface (deprecated, use --ws.addr) (default: "localhost")
  --wsport value                      WS-RPC server listening port (deprecated, use --ws.port) (default: 8546)
  --wsorigins value                   Origins from which to accept websockets requests (deprecated, use --ws.origins)
  --wsapi value                       API's offered over the WS-RPC interface (deprecated, use --ws.api)
  --gpoblocks value                   Number of recent blocks to check for gas prices (deprecated, use --gpo.blocks) (default: 20)
  --gpopercentile value               Suggested gas price is the given percentile of a set of recent transaction gas prices (deprecated, use --gpo.percentile) (default: 60)
  --graphql.addr value                GraphQL server listening interface (deprecated, graphql can only be enabled on the HTTP-RPC server endpoint, use --graphql)
  --graphql.port value                GraphQL server listening port (deprecated, graphql can only be enabled on the HTTP-RPC server endpoint, use --graphql) (default: 8545)
  --pprofport value                   pprof HTTP server listening port (deprecated, use --pprof.port) (default: 6060)
  --pprofaddr value                   pprof HTTP server listening interface (deprecated, use --pprof.addr) (default: "127.0.0.1")
  --memprofilerate value              Turn on memory profiling with the given rate (deprecated, use --pprof.memprofilerate) (default: 524288)
  --blockprofilerate value            Turn on block profiling with the given rate (deprecated, use --pprof.blockprofilerate) (default: 0)
  --cpuprofile value                  Write CPU profile to the given file (deprecated, use --pprof.cpuprofile)

MISC OPTIONS:
  --snapshot                          Enables snapshot-database mode -- experimental work in progress feature
  --help, -h                          show help


COPYRIGHT:
   Copyright 2013-2020 The go-ethereum Authors

這里列出了所有geth客戶端引數和注解,
我們會在我們適合的場景下,講解部分引數的使用說明,

2、同步以太放主網節點,
同步主網節點,需要滿足一下條件:
1、空余磁盤 500G 以上,目前,全球交易資料大約在350G 以上,
2、需要足夠的帶寬,

2.1 同步命令

mkdir /data
cd /data
mkdir gethdata
cd gethdata

編輯啟動腳本 start.sh

nohup ./geth --datadir="/data/gethdata" --rpc --rpcaddr=0.0.0.0 --rpcport=8545 --cache=512 --maxpeers 9999 --rpcapi="web3,eth,net,personal,db,admin" --rpccorsdomain="*" > ./geth.log &2>1

保存到start.sh

引數注解:

引數注解配置
- -datadirData directory for the databases and keystore (default: “/home/cuijb/.ethereum”)“/data/gethdata”
–rpcEnable the HTTP-RPC server (deprecated, use --http)
–rpcaddrHTTP-RPC server listening interface (deprecated, use --http.addr) (default: “localhost”)0.0.0.0(任何IP都可以,也可以指定固定IP)
–rpcportHTTP-RPC server listening port (deprecated, use --http.port) (default: 8545)8545(可以自定義)
–cacheMegabytes of memory allocated to internal caching (default = 4096 mainnet full node, 128 light mode) (default: 1024)512
–maxpeersMaximum number of network peers (network disabled if set to 0) (default: 50)9999
–rpcapiAPI’s offered over the HTTP-RPC interface (deprecated, use --http.api)“web3,eth,net,personal,db,admin”
–rpccorsdomainComma separated list of domains from which to accept cross origin requests (browser enforced) (deprecated, use --http.corsdomain)“*”

啟動腳本

sh start.sh

查看log,看到如下log資訊,此時已經同步了全球節點

INFO [09-10|15:57:09.796] Imported new chain segment               blocks=1     txs=162  mgas=12.484  elapsed=248.253ms mgasps=50.286  number=10832767 hash=8b5be8…08f966 dirty=127.90MiB
INFO [09-10|15:57:15.836] Imported new chain segment               blocks=1     txs=117  mgas=12.482  elapsed=344.367ms mgasps=36.245  number=10832768 hash=a38168…5aa6c3 dirty=127.90MiB
INFO [09-10|15:57:43.895] Imported new chain segment               blocks=1     txs=273  mgas=12.496  elapsed=1.216s    mgasps=10.275  number=10832769 hash=51bc39…2b681b dirty=127.90MiB
INFO [09-10|15:57:44.677] Imported new chain segment               blocks=1     txs=253  mgas=12.496  elapsed=774.446ms mgasps=16.135  number=10832770 hash=4485d1…e61833 dirty=127.90MiB
INFO [09-10|15:57:51.106] Imported new chain segment               blocks=1     txs=129  mgas=12.498  elapsed=441.170ms mgasps=28.330  number=10832771 hash=27c629…1d5dc2 dirty=127.90MiB
INFO [09-10|15:57:51.279] Chain reorg detected                     number=10832770 hash=4485d1…e61833 drop=1 dropfrom=27c629…1d5dc2 add=1 addfrom=055cd3…a29d53
INFO [09-10|15:57:51.280] Imported new chain segment               blocks=1     txs=116  mgas=12.486  elapsed=172.617ms mgasps=72.335  number=10832771 hash=055cd3…a29d53 dirty=127.90MiB
INFO [09-10|15:58:03.087] Imported new chain segment               blocks=1     txs=158  mgas=12.492  elapsed=340.944ms mgasps=36.639  number=10832772 hash=ebf6b0…f9aa4c dirty=127.90MiB
INFO [09-10|15:58:08.593] Deep froze chain segment                 blocks=6     elapsed=1.040s    number=10742771 hash=dc96e0…365518
INFO [09-10|15:58:13.424] Imported new chain segment               blocks=1     txs=151  mgas=12.481  elapsed=271.234ms mgasps=46.014  number=10832773 hash=bebad3…ee47d6 dirty=127.90MiB

啟動geth客戶端
剛才我們通過后臺的方式啟動了節點,通過以下方式打開geth客戶端,加載.ipc檔案的辦法啟動,我們查看如下引數,及說明,

引數說明
attachStart an interactive JavaScript environment (connect to node)

命令如下:

geth attach ipc:/data/gethdata/geth.ipc
//或者
geth attach ipc:http://192.168.31.43:8545

注解:兩種方式,都是打開geth客戶端,兩個命令,實作的功能有區別,第一個,可以開始挖礦,第二個無法開始,還有其他區別,大家研究,今天我們通過第一種辦法啟動,

顯示如下:

Welcome to the Geth JavaScript console!

instance: Geth/v1.9.9-stable-01744997/linux-amd64/go1.13.5
at block: 10832862 (Thu, 10 Sep 2020 16:18:02 CST)
 datadir: /data/gethdata
 modules: admin:1.0 debug:1.0 eth:1.0 ethash:1.0 miner:1.0 net:1.0 personal:1.0 rpc:1.0 txpool:1.0 web3:1.0
>

上面告訴你,啟動了ETH節點的模塊,

admin:1.0 debug:1.0 eth:1.0 ethash:1.0 miner:1.0 net:1.0 personal:1.0 rpc:1.0 txpool:1.0 web3:1.0

這些模塊的使用,會在后續的場景里,做介紹,

現在我們就可以與以太坊網路互動了,以太坊開發團隊提供了功能強大的客戶端互動工具及互動命令集web3.js,這部分內容,我們會在后續的章節里 詳細闡述,
如果操作全球節點,就需要自己購買以太坊,目前以太放價格是400美金一個,還是有點貴,

3、搭建以太放私有鏈節點
搭建私有鏈節點,可以更好的與區塊鏈互動,自己挖礦,挖出自己鏈上的ETH,方便操作網路,更方便我們除錯以太坊源代碼,甚至,我們可以開發出一套自己適用的區塊鏈出來,開始干吧,

3.1、創世塊
現在通過配置創世塊來創建私有鏈,同一個網路中,創世塊必須是一樣的,否則無法聯通,
創建一個eth的根目錄,在根目錄下新建創世塊json檔案genesis.json,

cd /data
mkdir gethdata
cd gethdata
vim genesis.json

粘貼如下內容

{
    "config": {
        "chainId": 8888,
        "homesteadBlock": 0,
        "daoForkBlock": 0,
        "daoForkSupport": true,
        "eip150Block": 0,
        "eip155Block": 0,
        "eip158Block": 0,
        "byzantiumBlock": 0,
        "constantinopleBlock": 0,
        "petersburgBlock": 0,
        "ethash": {}
    },
    "nonce": "0x42",
    "timestamp": "0x0",
    "extraData": "0x11bbe8db4e347b4e8c937c1c8370e4b5ed33adb3db69cbdb7a38e1e50b1b82fa",
    "gasLimit": "0xffffffff",
    "difficulty": "0x1",
    "alloc": {
        "093f59f1d91017d30d8c2caa78feb5beb0d2cfaf": {
            "balance": "0xffffffffffffffff"
        },
        "ddf7202cbe0aaed1c2d5c4ef05e386501a054406": {
            "balance": "0xffffffffffffffff"
        }
    }
}

保存檔案,輸入

:wq

退出編輯模式,

主網默認 chainId 1 ,我們搭建自己的私鏈,需要設定為 非 1 ,我們設定 8888即可,
引數解釋:

引數名稱引數描述
config鏈的一些基本配置
noncenonce就是一個64位亂數,用于挖礦,注意他和mixhash的設定需要滿足以太坊的Yellow paper, 4.3.4. Block Header Validity, (44)章節所描述的條件,
difficulty設定當前區塊的難度,如果難度過大,cpu挖礦就很難,這里設定較小難度
alloc用來預置賬號以及賬號的以太幣數量,因為私有鏈挖礦比較容易,所以我們不需要預置有幣的賬號,需要的時候自己創建即可以,
coinbase礦工的賬號,隨便填
timestamp設定創世塊的時間戳
extraData附加資訊,隨便填,可以填你的個性資訊
gasLimit該值設定對GAS的消耗總量限制,用來限制區塊能包含的交易資訊總和,因為我們是私有鏈,所以填最大,

3.2 啟動私有鏈節點
3.2.1 初始化區塊鏈

引數注解:

引數注解備注
initBootstrap and initialize a new genesis block建立創世區塊

命令如下

cd /data/
mkdir gethdata //已經創建檔案夾的,此處略過,
cd gethdata
geth --datadir "./" init genesis.json

顯示如下:

INFO [09-10|17:06:25.183] Maximum peer count                       ETH=50 LES=0 total=50
INFO [09-10|17:06:25.183] Smartcard socket not found, disabling    err="stat /run/pcscd/pcscd.comm: no such file or directory"
INFO [09-10|17:06:25.184] Set global gas cap                       cap=25000000
INFO [09-10|17:06:25.185] Allocated cache and file handles         database=/home/cuijb/geth/geth/chaindata cache=16.00MiB handles=16
INFO [09-10|17:06:25.231] Writing custom genesis block
INFO [09-10|17:06:25.232] Persisted trie from memory database      nodes=3 size=407.00B time="71.856μs" gcnodes=0 gcsize=0.00B gctime=0s livenodes=1 livesize=0.00B
INFO [09-10|17:06:25.232] Successfully wrote genesis state         database=chaindata                       hash="b25dc8…866dfa"
INFO [09-10|17:06:25.233] Allocated cache and file handles         database=/home/cuijb/geth/geth/lightchaindata cache=16.00MiB handles=16
INFO [09-10|17:06:25.239] Writing custom genesis block
INFO [09-10|17:06:25.240] Persisted trie from memory database      nodes=3 size=407.00B time="53.712μs" gcnodes=0 gcsize=0.00B gctime=0s livenodes=1 livesize=0.00B
INFO [09-10|17:06:25.240] Successfully wrote genesis state         database=lightchaindata                       hash="b25dc8…866dfa"

恭喜,創世區塊創建成功,

3.2.3、啟動區塊鏈網路

撰寫啟動腳本 start.sh

nohup geth  --rpc  --rpccorsdomain "*" --datadir "./" --port 30304 --rpcapi "db,eth,net,web3,personal,web3" --networkid 8888 --rpcport 8545 --rpcaddr "0.0.0.0" --allow-insecure-unlock  > ./geth.log &2>1

保存腳本,

這里需要特殊說明一下,私有鏈腳本與主網腳本的區別

引數注解備注
–networkidNetwork identifier (integer, 1=Frontier, 3=Ropsten, 4=Rinkeby, 5=G?rli) (default: 1)8888
–allow-insecure-unlockAllow insecure account unlocking when account-related RPCs are exposed by http

注解: 1、networkid 選項,主網配置為 1 ,其他3、4、5都是以太坊坊社區部署的測驗網路,我們是建立自己的私鏈,定義為8888,
2、allow-insecure-unlock選項,方便我們解鎖節點賬戶,如果是主網,不建議配置,否則,你存入節點賬戶的錢,會瞬間被黑客黑走,如何黑走,下面章節,分享黑客如何攻擊區塊鏈節點,

啟動腳本

sh start.sh

查看log,顯示如下:

cuijb@cuijb-VirtualBox:~/geth$ tail -f geth.log
INFO [09-10|20:09:02.427] Regenerated local transaction journal    transactions=0 accounts=0
INFO [09-10|20:09:02.433] Allocated fast sync bloom                size=512.00MiB
INFO [09-10|20:09:02.471] Initialized fast sync bloom              items=3 errorrate=0.000 elapsed=2.759ms
INFO [09-10|20:09:02.473] Starting peer-to-peer node               instance=Geth/v1.9.19-stable-3e064192/linux-amd64/go1.14.2
INFO [09-10|20:09:02.501] New local node record                    seq=1 id=68445c44ed2df2b1 ip=127.0.0.1 udp=30304 tcp=30304
INFO [09-10|20:09:02.504] IPC endpoint opened                      url=/home/cuijb/geth/geth.ipc
ERROR[09-10|20:09:02.504] Unavailable modules in HTTP API list     unavailable=[db] available="[admin debug web3 eth txpool personal ethash miner net]"
INFO [09-10|20:09:02.506] HTTP server started                      endpoint=[::]:8545 cors=* vhosts=localhost
INFO [09-10|20:09:02.519] Started P2P networking                   self=enode://36e36f39e9de61f999a1f03830487e11c62d244277e2a3dc8abc5985078560090e6938ef7cb506336433132983ec30653deb1addfca421161e21d691542c8a16@127.0.0.1:30304
INFO [09-10|20:09:04.330] New local node record                    seq=2 id=68445c44ed2df2b1 ip=223.74.158.88 udp=16706 tcp=30304
INFO [09-10|20:09:12.825] Looking for peers                        peercount=0 tried=102 static=0
INFO [09-10|20:09:24.156] Looking for peers                        peercount=0 tried=85  static=0
INFO [09-10|20:09:34.158] Looking for peers                        peercount=1 tried=64  static=0

如果,顯示這樣的資訊,我們就需要啟動礦工,
進入geth客戶端( Geth JavaScript console)
命令如下:

geth attach ipc:/data/gethdata/geth.ipc

顯示如下:

Welcome to the Geth JavaScript console!

instance: Geth/v1.9.19-stable-3e064192/linux-amd64/go1.14.2
at block: 0 (Thu Jan 01 1970 08:00:00 GMT+0800 (CST))
 datadir: /data/gethdata
 modules: admin:1.0 debug:1.0 eth:1.0 ethash:1.0 miner:1.0 net:1.0 personal:1.0 rpc:1.0 txpool:1.0 web3:1.0
>

輸入:

eth

如下:

 eth
{
  accounts: [],
  blockNumber: 0,
  coinbase: undefined,
  compile: {
    lll: function(),
    serpent: function(),
    solidity: function()
  },
  defaultAccount: undefined,
  defaultBlock: "latest",
  gasPrice: 1000000000,
  hashrate: 0,
  mining: false,
  pendingTransactions: [],
  protocolVersion: "0x41",
  syncing: false,
  call: function(),
  chainId: function(),
  contract: function(abi),
  estimateGas: function(),
  fillTransaction: function(),
  filter: function(options, callback, filterCreationErrorCallback),
  getAccounts: function(callback),
  getBalance: function(),
  getBlock: function(),
  getBlockByHash: function(),
  getBlockByNumber: function(),
  getBlockNumber: function(callback),
  getBlockTransactionCount: function(),
  getBlockUncleCount: function(),
  getCode: function(),
  getCoinbase: function(callback),
  getCompilers: function(),
  getGasPrice: function(callback),
  getHashrate: function(callback),
  getHeaderByHash: function(),
  getHeaderByNumber: function(),
  getMining: function(callback),
  getPendingTransactions: function(callback),
  getProof: function(),
  getProtocolVersion: function(callback),
  getRawTransaction: function(),
  getRawTransactionFromBlock: function(),
  getStorageAt: function(),
  getSyncing: function(callback),
  getTransaction: function(),
  getTransactionCount: function(),
  getTransactionFromBlock: function(),
  getTransactionReceipt: function(),
  getUncle: function(),
  getWork: function(),
  iban: function(iban),
  icapNamereg: function(),
  isSyncing: function(callback),
  namereg: function(),
  resend: function(),
  sendIBANTransaction: function(),
  sendRawTransaction: function(),
  sendTransaction: function(),
  sign: function(),
  signTransaction: function(),
  submitTransaction: function(),
  submitWork: function()
}

這里顯示與以太放網路互動的一些方法,
我們看到 accounts: [], 說明,我們還沒有創建賬戶,我們在節點上創建第一個賬戶,

創建賬戶

personal.newAccount("111111")
"0xbcb1ffd102fb09b4ad4558e53f9e06ed720ce7ed"

注解:personal.newAccount(“密碼”),這個密碼,就是我們要操作第一個賬戶的時候,使用的密碼,
查看賬戶

> eth.accounts
["0xbcb1ffd102fb09b4ad4558e53f9e06ed720ce7ed"]

我么再次geth客戶端,輸入 eth

> eth
{
  accounts: ["0xbcb1ffd102fb09b4ad4558e53f9e06ed720ce7ed"],
  blockNumber: 0,
  coinbase: "0xbcb1ffd102fb09b4ad4558e53f9e06ed720ce7ed",
  compile: {
    lll: function(),
    serpent: function(),
    solidity: function()
  },

我們可以清楚看到 accounts[]里多了一個地址,我們再多創建幾個地址,你們觀察一下,
你們會清楚的看到,accounts[0]=coinbase,

開始挖礦

miner.start()
null

你的礦工,開始幫我挖礦了,你很快就會變成很有錢的人了,

注解:miner.start(number),number默認不填,表示,啟動1個執行緒挖礦,你也可以多啟動幾個執行緒開始挖礦,那么number就設定多少,

查詢挖礦狀態

> eth.mining
true

true 說明,正在挖礦中,

停止挖礦

> miner.stop()
null

查詢挖礦狀態

> eth.mining
false

false 礦工停止挖礦

啟動礦工

miner.start()
null

我們開始查看log資訊

cuijb@cuijb-VirtualBox:~/geth$ tail -f geth.log
INFO [09-10|20:29:31.319] Generating DAG in progress               epoch=0 percentage=71 elapsed=5m55.753s
INFO [09-10|20:29:33.128] Looking for peers                        peercount=1 tried=60  static=0
INFO [09-10|20:29:36.133] Generating DAG in progress               epoch=0 percentage=72 elapsed=6m0.568s
INFO [09-10|20:29:41.135] Generating DAG in progress               epoch=0 percentage=73 elapsed=6m5.570s
INFO [09-10|20:29:43.227] Looking for peers                        peercount=1 tried=41  static=0
INFO [09-10|20:29:46.176] Generating DAG in progress               epoch=0 percentage=74 elapsed=6m10.611s
INFO [09-10|20:29:50.879] Generating DAG in progress               epoch=0 percentage=75 elapsed=6m15.314s
INFO [09-10|20:29:53.693] Looking for peers                        peercount=0 tried=79  static=0
INFO [09-10|20:29:55.444] Generating DAG in progress               epoch=0 percentage=76 elapsed=6m19.878s
INFO [09-10|20:30:00.043] Generating DAG in progress               epoch=0 percentage=77 elapsed=6m24.478s
INFO [09-10|20:30:03.743] Looking for peers                        peercount=1 tried=87  static=0
INFO [09-10|20:30:04.725] Generating DAG in progress               epoch=0 percentage=78 elapsed=6m29.159s
INFO [09-10|20:30:09.271] Generating DAG in progress               epoch=0 percentage=79 elapsed=6m33.706s
INFO [09-10|20:30:13.809] Looking for peers                        peercount=0 tried=18  static=0
INFO [09-10|20:30:14.240] Generating DAG in progress               epoch=0 percentage=80 elapsed=6m38.675s
INFO [09-10|20:30:19.477] Generating DAG in progress               epoch=0 percentage=81 elapsed=6m43.912s
INFO [09-10|20:30:24.011] Looking for peers                        peercount=0 tried=94  static=0
INFO [09-10|20:30:24.489] Generating DAG in progress               epoch=0 percentage=82 elapsed=6m48.924s
INFO [09-10|20:30:29.588] Generating DAG in progress               epoch=0 percentage=83 elapsed=6m54.023s
INFO [09-10|20:30:34.314] Looking for peers                        peercount=1 tried=80  static=0
INFO [09-10|20:30:34.316] Generating DAG in progress               epoch=0 percentage=84 elapsed=6m58.751s
INFO [09-10|20:30:39.184] Generating DAG in progress               epoch=0 percentage=85 elapsed=7m3.619s
INFO [09-10|20:30:44.269] Generating DAG in progress               epoch=0 percentage=86 elapsed=7m8.703s
INFO [09-10|20:30:44.447] Looking for peers                        peercount=0 tried=65  static=0
INFO [09-10|20:30:49.497] Generating DAG in progress               epoch=0 percentage=87 elapsed=7m13.932s
INFO [09-10|20:30:54.345] Generating DAG in progress               epoch=0 percentage=88 elapsed=7m18.780s
INFO [09-10|20:30:54.475] Looking for peers                        peercount=1 tried=69  static=0
INFO [09-10|20:30:59.214] Generating DAG in progress               epoch=0 percentage=89 elapsed=7m23.649s
INFO [09-10|20:31:04.078] Generating DAG in progress               epoch=0 percentage=90 elapsed=7m28.513s
INFO [09-10|20:31:04.477] Looking for peers                        peercount=0 tried=29  static=0
INFO [09-10|20:31:09.165] Generating DAG in progress               epoch=0 percentage=91 elapsed=7m33.599s
INFO [09-10|20:31:14.419] Generating DAG in progress               epoch=0 percentage=92 elapsed=7m38.854s
INFO [09-10|20:31:14.640] Looking for peers                        peercount=2 tried=107 static=0
INFO [09-10|20:31:19.658] Generating DAG in progress               epoch=0 percentage=93 elapsed=7m44.093s
INFO [09-10|20:31:24.834] Generating DAG in progress               epoch=0 percentage=94 elapsed=7m49.269s
INFO [09-10|20:31:30.079] Generating DAG in progress               epoch=0 percentage=95 elapsed=7m54.514s
INFO [09-10|20:31:34.749] Looking for peers                        peercount=1 tried=24  static=0
INFO [09-10|20:31:34.943] Generating DAG in progress               epoch=0 percentage=96 elapsed=7m59.378s
INFO [09-10|20:31:40.429] Generating DAG in progress               epoch=0 percentage=97 elapsed=8m4.864s
INFO [09-10|20:31:44.820] Looking for peers                        peercount=1 tried=101 static=0
INFO [09-10|20:31:45.436] Generating DAG in progress               epoch=0 percentage=98 elapsed=8m9.871s
INFO [09-10|20:31:50.699] Generating DAG in progress               epoch=0 percentage=99 elapsed=8m15.134s
INFO [09-10|20:31:50.702] Generated ethash verification cache      epoch=0 elapsed=8m15.137s
INFO [09-10|20:31:52.354] Successfully sealed new block            number=1 sealhash="b1077b…7283ce" hash="3de7b9…309a81" elapsed=8m17.473s
INFO [09-10|20:31:52.354] 🔨 mined potential block                  number=1 hash="3de7b9…309a81"
INFO [09-10|20:31:52.375] Commit new mining work                   number=2 sealhash="ac6dd9…0f2149" uncles=0 txs=0 gas=0 fees=0 elapsed="139.91μs"
INFO [09-10|20:31:54.845] Looking for peers                        peercount=1 tried=46  static=0
INFO [09-10|20:32:02.128] Generating DAG in progress               epoch=1 percentage=0  elapsed=9.724s
INFO [09-10|20:32:04.014] Successfully sealed new block            number=2 sealhash="ac6dd9…0f2149" hash="1297c3…6287c5" elapsed=11.639s
INFO [09-10|20:32:04.015] 🔨 mined potential block                  number=2 hash="1297c3…6287c5"
INFO [09-10|20:32:04.015] Commit new mining work                   number=3 sealhash="b05dc9…0b3b20" uncles=0 txs=0 gas=0 fees=0 elapsed="149.168μs"
INFO [09-10|20:32:04.764] Successfully sealed new block            number=3 sealhash="b05dc9…0b3b20" hash="3ef80c…559305" elapsed=749.123ms
INFO [09-10|20:32:04.764] 🔨 mined potential block                  number=3 hash="3ef80c…559305"
INFO [09-10|20:32:04.765] Commit new mining work                   number=4 sealhash="c42df7…426749" uncles=0 txs=0 gas=0 fees=0 elapsed="98.08μs"
INFO [09-10|20:32:05.117] Looking for peers                        peercount=1 tried=72  static=0
INFO [09-10|20:32:08.364] Successfully sealed new block            number=4 sealhash="c42df7…426749" hash="9ef7c2…9c4a9f" elapsed=3.599s
INFO [09-10|20:32:08.364] 🔨 mined potential block                  number=4 hash="9ef7c2…9c4a9f"
INFO [09-10|20:32:08.365] Commit new mining work                   number=5 sealhash="d780b4…9ef989" uncles=0 txs=0 gas=0 fees=0 elapsed="239.711μs"
INFO [09-10|20:32:08.670] Successfully sealed new block            number=5 sealhash="d780b4…9ef989" hash="110d9b…b27f30" elapsed=305.643ms
INFO [09-10|20:32:08.671] 🔨 mined potential block                  number=5 hash="110d9b…b27f30"

注解:
1、Generating DAG in progress 中 percentage 一定要達到 100
后,網路才能啟動,礦工開始有收益,
2、顯示 Successfully sealed new block number=1 sealhash=“b1077b…7283ce” hash=“3de7b9…309a81” elapsed=8m17.473s 說明,礦工已經開始作業,礦工已經開始幫主人賺錢了,

查看我們的收益,輸入如下命令:
切換geth客戶端

eth.getBalance(eth.accounts[0])
120000000000000000000

礦工才開始作業,我的賬戶有很多 ETH幣,其實不要多想,我們看到的數量單位只是Wei,

3.2、Ether幣的基本單位
Ether幣最小的單位是Wei,也是命令列默認的單位, 然后每1000個進一個單位,依次是

  • kwei (1000 Wei)
  • mwei (1000 KWei)
  • gwei (1000 mwei)
  • szabo (1000 gwei)
  • finney (1000 szabo)
  • ether (1000 finney)

簡單地說就是就是1 以太幣 = 1000000000000000000 Wei (10的18次方wei)

上面查詢余額,其實是很少的,

3.3 、如何進行ether 和 Wei之間的轉換

Ether–> Wei:web3.toWei

> web3.toWei(1)
"1000000000000000000"
> web3.toWei(1.2345678)
"1234567800000000000"
>

Wei –> Ether: web3.fromWei

> web3.fromWei(10000000000000000)
"0.01"
> web3.fromWei(1000000000000000000)
"1"
>

現在再次查詢一下,我的余額

> web3.fromWei(eth.getBalance(eth.coinbase))
1566

3.4 轉賬操作
再創建一個賬戶

> personal.newAccount("111111")
"0xab9836f46e51fb4e25e3aaa248a441d86595b628"

查詢賬戶串列

> eth.accounts
["0xbcb1ffd102fb09b4ad4558e53f9e06ed720ce7ed", "0xab9836f46e51fb4e25e3aaa248a441d86595b628"]

開始轉賬

/*定義第一個賬戶*/
> acc0=eth.accounts[0]
"0xbcb1ffd102fb09b4ad4558e53f9e06ed720ce7ed"
/*定義第二個賬戶*/
> acc1=eth.accounts[1]
"0xab9836f46e51fb4e25e3aaa248a441d86595b628"
/*定義轉賬金額,轉為為Wei*/
> amount = web3.toWei(12.345)
"12345000000000000000"
/*解鎖第一個賬戶*/
> personal.unlockAccount(acc0)
Unlock account 0xbcb1ffd102fb09b4ad4558e53f9e06ed720ce7ed
Passphrase:
true
/*開始轉賬*/
> eth.sendTransaction({from:acc0,to:acc1,value:amount})
"0xd2ee2d8c73bad76e07d0c7d7551ca2dc0ea5ac615cfb627408853d67b1ad1819"
/*查詢第二個賬戶余額*/
> web3.fromWei(eth.getBalance(acc1))
12.345
/*鏈上查詢這筆交易情況*/
> eth.getTransaction("0xd2ee2d8c73bad76e07d0c7d7551ca2dc0ea5ac615cfb627408853d67b1ad1819")
{
  blockHash: "0xf35ddb73525baeecb248045908568f752bd9b2fb77f78da0532778219360729f",
  blockNumber: 828,
  from: "0xbcb1ffd102fb09b4ad4558e53f9e06ed720ce7ed",
  gas: 21000,
  gasPrice: 1000000000,
  hash: "0xd2ee2d8c73bad76e07d0c7d7551ca2dc0ea5ac615cfb627408853d67b1ad1819",
  input: "0x",
  nonce: 0,
  r: "0x31ef99aa435375cfc90d33ff25314868586ba8967ff2d0e1bc44a9ac32891b0e",
  s: "0x3655f99471c93ed9894edc0dffdf281fba8b081bc9dbd07dfaa241c5a77ff105",
  to: "0xab9836f46e51fb4e25e3aaa248a441d86595b628",
  transactionIndex: 0,
  v: "0x4594",
  value: 12345000000000000000
}
/*鏈上查詢這筆交易憑據*/
>eth.getTransactionReceipt("0xd2ee2d8c73bad76e07d0c7d7551ca2dc0ea5ac615cfb627408853d67b1ad1819")
{
  blockHash: "0xf35ddb73525baeecb248045908568f752bd9b2fb77f78da0532778219360729f",
  blockNumber: 828,
  contractAddress: null,
  cumulativeGasUsed: 21000,
  from: "0xbcb1ffd102fb09b4ad4558e53f9e06ed720ce7ed",
  gasUsed: 21000,
  logs: [],
  logsBloom: "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
  status: "0x1",
  to: "0xab9836f46e51fb4e25e3aaa248a441d86595b628",
  transactionHash: "0xd2ee2d8c73bad76e07d0c7d7551ca2dc0ea5ac615cfb627408853d67b1ad1819",
  transactionIndex: 0
}
>

我們體驗了一次從 account[0] ----> account[1] 轉移了 12.345 個ETH 的程序,

通過這兩章的練習,我們思考一下:
1、轉移的12.345個ETH,區塊鏈將資料保存在哪里,
2、通過這筆轉賬,我們思考一下 ,一個交易的生命周期,

大家可以將自己的思考,在下面留言,一起交流,

2020年9月10日晚,

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/22145.html

標籤:python

上一篇:演算法——歐幾里得演算法

下一篇:Forsage以太坊智能合約是什么

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • 【C++】Microsoft C++、C 和匯編程式檔案

    ......

    uj5u.com 2020-09-10 00:57:23 more
  • 例外宣告

    相比于斷言適用于排除邏輯上不可能存在的狀態,例外通常是用于邏輯上可能發生的錯誤。 例外宣告 Item 1:當函式不可能拋出例外或不能接受拋出例外時,使用noexcept 理由 如果不打算拋出例外的話,程式就會認為無法處理這種錯誤,并且應當盡早終止,如此可以有效地阻止例外的傳播與擴散。 示例 //不可 ......

    uj5u.com 2020-09-10 00:57:27 more
  • Codeforces 1400E Clear the Multiset(貪心 + 分治)

    鏈接:https://codeforces.com/problemset/problem/1400/E 來源:Codeforces 思路:給你一個陣列,現在你可以進行兩種操作,操作1:將一段沒有 0 的區間進行減一的操作,操作2:將 i 位置上的元素歸零。最終問:將這個陣列的全部元素歸零后操作的最少 ......

    uj5u.com 2020-09-10 00:57:30 more
  • UVA11610 【Reverse Prime】

    本人看到此題沒有翻譯,就附帶了一個自己的翻譯版本 思考 這一題,它的第一個要求是找出所有 $7$ 位反向質數及其質因數的個數。 我們應該需要質數篩篩選1~$10^{7}$的所有數,這里就不慢慢介紹了。但是,重讀題,我們突然發現反向質數都是 $7$ 位,而將它反過來后的數字卻是 $6$ 位數,這就說明 ......

    uj5u.com 2020-09-10 00:57:36 more
  • 統計區間素數數量

    1 #pragma GCC optimize(2) 2 #include <bits/stdc++.h> 3 using namespace std; 4 bool isprime[1000000010]; 5 vector<int> prime; 6 inline int getlist(int ......

    uj5u.com 2020-09-10 00:57:47 more
  • C/C++編程筆記:C++中的 const 變數詳解,教你正確認識const用法

    1、C中的const 1、區域const變數存放在堆疊區中,會分配記憶體(也就是說可以通過地址間接修改變數的值)。測驗代碼如下: 運行結果: 2、全域const變數存放在只讀資料段(不能通過地址修改,會發生寫入錯誤), 默認為外部聯編,可以給其他源檔案使用(需要用extern關鍵字修飾) 運行結果: ......

    uj5u.com 2020-09-10 00:58:04 more
  • 【C++犯錯記錄】VS2019 MFC添加資源不懂如何修改資源宏ID

    1. 首先在資源視圖中,添加資源 2. 點擊新添加的資源,復制自動生成的ID 3. 在解決方案資源管理器中找到Resource.h檔案,編輯,使用整個專案搜索和替換的方式快速替換 宏宣告 4. Ctrl+Shift+F 全域搜索,點擊查找全部,然后逐個替換 5. 為什么使用搜索替換而不使用屬性視窗直 ......

    uj5u.com 2020-09-10 00:59:11 more
  • 【C++犯錯記錄】VS2019 MFC不懂的批量添加資源

    1. 打開資源頭檔案Resource.h,在其中預先定義好宏 ID(不清楚其實ID值應該設定多少,可以先新建一個相同的資源項,再在這個資源的ID值的基礎上遞增即可) 2. 在資源視圖中選中專案資源,按F7編輯資源檔案,按 ID 型別 相對路徑的形式添加 資源。(別忘了先把檔案拷貝到專案中的res檔案 ......

    uj5u.com 2020-09-10 01:00:19 more
  • C/C++編程筆記:關于C++的參考型別,專供新手入門使用

    今天要講的是C++中我最喜歡的一個用法——參考,也叫別名。 參考就是給一個變數名取一個變數名,方便我們間接地使用這個變數。我們可以給一個變數創建N個參考,這N + 1個變數共享了同一塊記憶體區域。(參考型別的變數會占用記憶體空間,占用的記憶體空間的大小和指標型別的大小是相同的。雖然參考是一個物件的別名,但 ......

    uj5u.com 2020-09-10 01:00:22 more
  • 【C/C++編程筆記】從頭開始學習C ++:初學者完整指南

    眾所周知,C ++的學習曲線陡峭,但是花時間學習這種語言將為您的職業帶來奇跡,并使您與其他開發人員區分開。您會更輕松地學習新語言,形成真正的解決問題的技能,并在編程的基礎上打下堅實的基礎。 C ++將幫助您養成良好的編程習慣(即清晰一致的編碼風格,在撰寫代碼時注釋代碼,并限制類內部的可見性),并且由 ......

    uj5u.com 2020-09-10 01:00:41 more
最新发布
  • Rust中的智能指標:Box<T> Rc<T> Arc<T> Cell<T> RefCell<T> Weak

    Rust中的智能指標是什么 智能指標(smart pointers)是一類資料結構,是擁有資料所有權和額外功能的指標。是指標的進一步發展 指標(pointer)是一個包含記憶體地址的變數的通用概念。這個地址參考,或 ” 指向”(points at)一些其 他資料 。參考以 & 符號為標志并借用了他們所 ......

    uj5u.com 2023-04-20 07:24:10 more
  • Java的值傳遞和參考傳遞

    值傳遞不會改變本身,參考傳遞(如果傳遞的值需要實體化到堆里)如果發生修改了會改變本身。 1.基本資料型別都是值傳遞 package com.example.basic; public class Test { public static void main(String[] args) { int ......

    uj5u.com 2023-04-20 07:24:04 more
  • [2]SpinalHDL教程——Scala簡單入門

    第一個 Scala 程式 shell里面輸入 $ scala scala> 1 + 1 res0: Int = 2 scala> println("Hello World!") Hello World! 檔案形式 object HelloWorld { /* 這是我的第一個 Scala 程式 * 以 ......

    uj5u.com 2023-04-20 07:23:58 more
  • 理解函式指標和回呼函式

    理解 函式指標 指向函式的指標。比如: 理解函式指標的偽代碼 void (*p)(int type, char *data); // 定義一個函式指標p void func(int type, char *data); // 宣告一個函式func p = func; // 將指標p指向函式func ......

    uj5u.com 2023-04-20 07:23:52 more
  • Django筆記二十五之資料庫函式之日期函式

    本文首發于公眾號:Hunter后端 原文鏈接:Django筆記二十五之資料庫函式之日期函式 日期函式主要介紹兩個大類,Extract() 和 Trunc() Extract() 函式作用是提取日期,比如我們可以提取一個日期欄位的年份,月份,日等資料 Trunc() 的作用則是截取,比如 2022-0 ......

    uj5u.com 2023-04-20 07:23:45 more
  • 一天吃透JVM面試八股文

    什么是JVM? JVM,全稱Java Virtual Machine(Java虛擬機),是通過在實際的計算機上仿真模擬各種計算機功能來實作的。由一套位元組碼指令集、一組暫存器、一個堆疊、一個垃圾回收堆和一個存盤方法域等組成。JVM屏蔽了與作業系統平臺相關的資訊,使得Java程式只需要生成在Java虛擬機 ......

    uj5u.com 2023-04-20 07:23:31 more
  • 使用Java接入小程式訂閱訊息!

    更新完微信服務號的模板訊息之后,我又趕緊把微信小程式的訂閱訊息給實作了!之前我一直以為微信小程式也是要企業才能申請,沒想到小程式個人就能申請。 訊息推送平臺🔥推送下發【郵件】【短信】【微信服務號】【微信小程式】【企業微信】【釘釘】等訊息型別。 https://gitee.com/zhongfuch ......

    uj5u.com 2023-04-20 07:22:59 more
  • java -- 緩沖流、轉換流、序列化流

    緩沖流 緩沖流, 也叫高效流, 按照資料型別分類: 位元組緩沖流:BufferedInputStream,BufferedOutputStream 字符緩沖流:BufferedReader,BufferedWriter 緩沖流的基本原理,是在創建流物件時,會創建一個內置的默認大小的緩沖區陣列,通過緩沖 ......

    uj5u.com 2023-04-20 07:22:49 more
  • Java-SpringBoot-Range請求頭設定實作視頻分段傳輸

    老實說,人太懶了,現在基本都不喜歡寫筆記了,但是網上有關Range請求頭的文章都太水了 下面是抄的一段StackOverflow的代碼...自己大修改過的,寫的注釋挺全的,應該直接看得懂,就不解釋了 寫的不好...只是希望能給視頻網站開發的新手一點點幫助吧. 業務場景:視頻分段傳輸、視頻多段傳輸(理 ......

    uj5u.com 2023-04-20 07:22:42 more
  • Windows 10開發教程_編程入門自學教程_菜鳥教程-免費教程分享

    教程簡介 Windows 10開發入門教程 - 從簡單的步驟了解Windows 10開發,從基本到高級概念,包括簡介,UWP,第一個應用程式,商店,XAML控制元件,資料系結,XAML性能,自適應設計,自適應UI,自適應代碼,檔案管理,SQLite資料庫,應用程式到應用程式通信,應用程式本地化,應用程式 ......

    uj5u.com 2023-04-20 07:22:35 more