preface

The pit blockchain, for the first blockchain technology to the peak of bitcoin can not not understand. The best way to understand the application of a technology is to personally compile and read the source code of Bitcoin, although I can not do, but willing to try. I thought, the journey may be difficult, there will be beautiful scenery waiting for me at the end.

Recommended mastery of bitcoin second edition, explain the principle of bitcoin is a very good book.

bitcoinGithub project introduction

Open the Github address of Bitcoin, we can find a total of four directories:

  • Bitcoin core source code C++

  • Bips documentation on bitcoin improvement suggestions

  • Libbase58 Bitcoin Base58 codec library C

  • Libblkmaker Bitcoin block template library C

Open Bitcoin and take a look at the architecture of the core code:

Roll up your sleeves

1. Pull the corresponding bitcoin source code from Github
// pull bitcoiin source gitclone0.16 HTTP: / / https://github.com/bitcoin/bitcoin.git / / switch version to the latest git checkoutCopy the code
2. Follow the official build document

Looking at the official build documentation, I was surprised to find that Bitcoin can be built and debugged using Qt. With an IDE, when looking at the source code, the related functions can jump directly to the defined place. How much easier…

Follow the steps, do not drop one step, or there may be unexpected obstacles behind. About 10min, the whole build process is finished.

3. Several main procedures
  • Bitcoiin Core. App Bitcoiin client graphical interface version

  • Bitcoind/SRC/Bitcoind bitcoind is a concise command line version that will be the focus of the next step of source code analysis (cannot be run with Bitcoin Core, if you accidentally try to run another client at the same time, it will tell you that a client is already running and exit automatically)

  • Bitcoind -cli/SRC/Bitcoind -cli Bitcoind is a full-featured RPC client that can query a block information, transaction information, etc from the command line

  • Bitcoin-tx/SRC/Bitcoind Bitcoin transaction processing module, which can be used for transaction query and creation

bitcoind

1. Start and end Bitcoind
cd. /bitcoind //2 /bitcoind //2 /bitcoind //2 /bitcoind //2 /bitcoind // Start and specify number of synchronizations./bitcoind - maxConnections =0 //3. /bitcoin-cli invalidateBlock 'bitcoin-cli getBestBlockHash' //4. End. / bitcoins - cli stopCopy the code
noteIf you suddenly find yourself running out of memory on your Mac, it’s Bitcoin! The default block sync path on Mac is easy to find, so you don’t know where to find it:
/Users/[User]/Library/Application Support/Bitcoin/blocks
Copy the code
2. Bitcoind Other commands

./bitcoind -help you can view the various commands and parameter formats supported by Bitcoind:

Bitcoind [option] bitcoind [option] < command > [parameter] Send command to -server or bitcoind [option]helpList the command bitcoind [options]helpBitcoind -conf=< file name > Specify configuration file (default: bitcoin.conf) -pid=< file name > Specify PID (process ID) file (default: Bitcoind.pid) -gen Generate bitcoins -gen=0 Do not generate bitcoins -min minimize when startup -splash Display startup screen when startup (default: 1) -datadir=< directory name > Specify data directory -dbCache =<n style="word-wrap: break-word;"> Set the database cache size in megabytes (MB) (default: 25) </n> -dblogsize=<n style="word-wrap: break-word;"> Set the database disk log size in megabytes (MB) (default: 100) </n> -timeout=<n style="word-wrap: break-word;"</n> -proxy=< IP: port style="word-wrap: break-word;"-dns addNode allows DNS queries and connections through Socks4 proxy </ IP: port > -port=< port > Listen for connections on < port > (default: 8333, test network testnet: 18333) - maxconnections = < n style ="word-wrap: break-word;""> < p style=" max-width: 100%; clear: both; min-height: 1em"word-wrap: break-word;"</n></n> -addNode =< IP style="word-wrap: break-word;"> add a node to connect to and try to maintain a connection to that node </ IP > -connect=< IP style="word-wrap: break-word;"-IRC uses IRC (Internet Relay chat) to find nodes (default: 0) -LISTEN accepts connections from outside (default: 1) -dnsseed uses DNS to find nodes (default: 1) -banscore=<n style="word-wrap: break-word;"> Threshold for disconnecting from an abnormal node (default: 100) </n> -bantime=<n style="word-wrap: break-word;"> Number of seconds between abnormal node connections (default: 86400) </n> -maxReceiveBuffer =<n style="word-wrap: break-word;"< p style= "max-width: 100%; clear: both; min-height: 1em"word-wrap: break-word;">*1000 bytes (default: 10000) </n></n> -maxSendBuffer =<n style="word-wrap: break-word;"< p style= "max-width: 100%; clear: both; min-height: 1em"word-wrap: break-word;">*1000 bytes (default: 10000) </n></n> - UPNP uses global plug and play (UPNP) mapping to listen on the port (default: 0) - detachDB separates the currency block from the address database. Will increase the client shutdown time (default: 0) -paytxfee=<amt style="word-wrap: break-word;"> Handling charges per kilobyte for the transactions you send </ amT > - Testnet uses the test network -debug prints additional debugging information -logtimestamps Add [timestamp](http://8btc.com/article-165-1.html) - printToConsole sends trace/debug information toconsole instead of debug.log file - printtoDebugger Sending trace/debugging information to the debugger -rpcuser=< User name > JSON -user name used for RPC connection -rpcPassword =< password > Json-RPC connection password -rpcport=<port style="word-wrap: break-word;"> json-rpc connection < port> (default: 8332) </port> -rpcallowip=< IP style="word-wrap: break-word;"> allow from specified < IP style="word-wrap: break-word;"> Address jSON-RPC connection </ IP ></ IP > -rpcconnect=< IP style="word-wrap: break-word;"> send the command to run at < IP style="word-wrap: break-word;"> address node (default: 127.0.0.1) </ IP ></ IP > -Blocknotify =< command > Execute command when the best currency block changes (%s in the command will be replaced with the currency block hash value) - upgradeWallet upgrades the wallet to the latest format -keypool=<n style="word-wrap: break-word;"< p style= "max-width: 100%; clear: both; min-height: 1em"word-wrap: break-word;"> (default: 100) </n></n> -rescan rescan the currency block chain to find wallet missing transactions -checkblocks=<n style="word-wrap: break-word;"</n> -checklevel=<n style="word-wrap: break-word;"> Level of currency block authentication (0-6, default: 1) </n> **SSL options: * * - RPCSSL using OpenSSL (HTTPS) JSON xml-rpc connection - rpcsslcertificatechainfile = < file. Cert > server certificate file (default: Server-cert) -rpcsslPrivateKeyFile =< file. pem> Server privatekeyfile (default: server.pem) -rpcSSLciphers =< Password > Acceptable password (default: TLSv1+HIGH:! SSLv2:! aNULL:! eNULL:! AH:! 3 des: @ STRENGTH)Copy the code

bitcoin-cli

Bitcoin Core contains a fully functional RPC client that can query blocks, wallets, transactions and other information. Bitcoin uses a JSON-RPC interface.

1. Command example
/ / get the height of 0 blocks hash. / SRC/bitcoins - cli getblockhash d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f 0 000000000019 / / get a hash blocks known specific information. / SRC/bitcoins - cli getblock d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f {000000000019"hash": "000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f"."confirmations": 187783,
  "strippedsize": 285,
  "size": 285,
  "weight": 1140,
  "height": 0."version": 1,
  "versionHex": "00000001"."merkleroot": "4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b"."tx": [
    "4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b"]."time": 1231006505,
  "mediantime": 1231006505,
  "nonce": 2083236893,
  "bits": "1d00ffff"."difficulty": 1,
  "chainwork": "0000000000000000000000000000000000000000000000000000000100010001"."nextblockhash": "00000000839a8e6886ab5951d76f411475428afc90947ee320161bbf18eb6048"
}

Copy the code
2. Other commands
A, general command // help instructionhelp ( "command"Ping getNettotals getNetworkInfo getPeerInfo getConnectionCount verifychain ( checklevel numblocks ) getaddednodeinfo dns ("node" )
addnode "node" "add|remove|onetry"B, wallet, account, address, transfer, message getwalletInfo // getwallet information walletpassphrase"passphrase"Timeout // Unlock wallet password - how long does the wallet automatically lock WalletLock // Lock the wallet WalletPassphrasechange"oldpassphrase" "newpassphrase"// Change the wallet password backupWallet"destination"// The wallet backup importwallet"filename"// Import the wallet backup file into dumpWallet"filename"// Wallet restore listAccounts (minconf) // List all user getAddressesbyAccounts"account"Getaccountaddress lists all wallet addresses of the user"account"
getaccount "bitcoinaddress"
validateaddress "bitcoinaddress"
dumpprivkey "bitcoinaddress"
setaccount "bitcoinaddress" "account"
getnewaddress ( "account"Keypoolrefill (newsize) importprivKey"bitcoinprivkey" ( "label"// Import private key createmultisig nRequired ["key". ]  addmultisigaddress nrequired ["key". ] ("account" )

getbalance ( "account"Getunconfirmedbalance GetunconfirmedBalance GetReceivedByAccount Gets the number of Bitcoins corresponding to Account or BitCoinAddress"account" ( minconf )
getreceivedbyaddress "bitcoinaddress" ( minconf )

listreceivedbyaccount ( minconf includeempty )
listreceivedbyaddress ( minconf includeempty )
move "fromaccount" "toaccount" amount ( minconf "comment" )
listunspent ( minconf maxconf  ["address". ]  ) listlockunspent lockunspent unlock [{"txid":"txid"."vout":n},... ]  getrawchangeaddress listaddressgroupings settxfee amount sendtoaddress"bitcoinaddress" amount ( "comment" "comment-to" )
sendfrom "fromaccount" "tobitcoinaddress" amount ( minconf "comment" "comment-to" )
sendmany "fromaccount" {"address":amount,... } ( minconf"comment" )

signmessage "bitcoinaddress" "message"
verifymessage "bitcoinaddress" "signature" "message"C, Tx, Block, Ming createrawTransaction [{"txid":"id"."vout":n},... ] {"address":amount,... } signrawtransaction"hexstring"([{"txid":"id"."vout":n,"scriptPubKey":"hex"."redeemScript":"hex"},... ] ["privatekey1". ]  sighashtype ) sendrawtransaction"hexstring" ( allowhighfees )


gettransaction "txid"Getrawtransaction = getrawTransaction = getrawTransaction"txid"(verbose) // Get a hexadecimal string decoderawTransaction that describes the transaction"hexstring"// Decode the above string listTransactions ("account"Listsinceblock (count from)"blockhash" target-confirmations )


getrawmempool ( verbose )
gettxoutsetinfo
gettxout "txid" n ( includemempool )

decodescript "hex"

getblockchaininfo
getblockcount
getbestblockhash
getblockhash index
getblock "hash" ( verbose )

getmininginfo
getdifficulty
getnetworkhashps ( blocks height )
gethashespersec                                                                                                                                                       
getgenerate
setgenerate generate ( genproclimit )
getwork ( "data" )
getblocktemplate ( "jsonrequestobject" )
submitblock "hexdata" ( "jsonparametersobject" )
Copy the code

The compilation of bitcoin source code under Mac is complete, and we also understand bitcoind and bitcoin-CLI basic commands. The long march has finally taken its first step, and that’s all for today.

The next chapter is to understand the overall framework of Bitcoin source code and the function of the code module.

The Internet disrupts the world, blockchain disrupts the Internet!

— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — 20180417 23:08