以太坊物聯網區塊鏈(一)
Web3js 與 java 連接區塊鏈可以參考我github上的兩個小demo
Ethereum-java
Ethereum-javascript
搭建私有鏈, 利用以太坊平臺完成資料上鏈
如何搭建?
用Geth搭建一個區塊鏈節點,本地主機就和區塊鏈網路中主機一致了,(可以連接main鏈,和其它測驗鏈,還有自定義鏈),注:可以通過賦予chainid和networkid不同的值讓本機成為連接在main鏈chainid(1),測驗鏈chanid(2-4)或者自定義鏈chainid(其它,暫設定為666)
chainid 與 networkid 具體用途,建議設定成一樣,后面省心
安裝geth
一臺新機器 Ubuntu 20.04LTS (虛擬機)
#新機器需要做以下兩步
#更換清華的源,參考網上
#安裝vim,參考網上
#執行下列命令
sudo apt-get update
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
創世塊檔案
#在桌面創建 mkdir privateblock && cd privateblock
#創建創世塊檔案genesis.json,并將下列內容放入genesis.json檔案中
{
"config": {
"chainId": 666,
"homesteadBlock": 0,
"eip150Block": 0,
"eip150Hash": "0x0000000000000000000000000000000000000000000000000000000000000000",
"eip155Block": 0,
"eip158Block": 0,
"byzantiumBlock": 0,
"constantinopleBlock": 0,
"petersburgBlock": 0,
"istanbulBlock": 0,
"ethash": {}
},
"nonce": "0x0",
"timestamp": "0x5ddf8f3e",
"extraData": "0x0000000000000000000000000000000000000000000000000000000000000000",
"gasLimit": "0x47b760",
"difficulty": "0x00002",
"mixHash": "0x0000000000000000000000000000000000000000000000000000000000000000",
"coinbase": "0x0000000000000000000000000000000000000000",
"alloc": {
"bc9a3ece02d7cb31cf63dfdfc48db0b82770d014": {
"balance": "8000000000000000000000000000000"
}
},
"number": "0x0",
"gasUsed": "0x0",
"parentHash": "0x0000000000000000000000000000000000000000000000000000000000000000"
}
#打開geth之前一定要進入privateblock目錄,初始化創世塊檔案,每臺主機只需要初始化一次
geth --datadir data init genesis.json
打開Geth客戶端
Geth版本:
Welcome to the Geth JavaScript console!
instance: Geth/v1.10.8-stable-26675454/linux-amd64/go1.16.4
#下面是我撰寫的開啟geth腳本
root@blockchain1:/home/chenhui/privateblock# cat frist_start_2.sh
#!/bin/bash
nohup geth --datadir data --networkid 666 --http --http.corsdomain="*" --http.port 8545 --http.addr "0.0.0.0" --http.api db,web3,eth,debug,personal,net,miner,admin --allow-insecure-unlock --rpc.allow-unprotected-txs --port 30303 --dev --dev.period 1 2>./console.log &
Geth操作命令
#創建賬戶 123為賬戶密碼
personal.newAccount("12345678")
#查看第一個賬戶
eth.accounts[0]
#查看用戶
eth.accounts
#查看礦工賬戶,若節點中有多個賬戶,默認第一個賬戶為礦工賬戶
eth.coinbase
#查看區塊數量
eth.blockNumber
#通過區塊號,查看區塊資訊
eth.getBlock(i)
#給賬戶地址取別名
user1=eth.accounts[0]
#通過別名獲取金額
eth.getBalance(user1)
#轉賬之前需要解鎖密碼,直接回車,默認賬號鎖定密碼為空,回傳true成功
personal.unlockAccount(user1)
#賬戶之間轉賬,提交交易,但是還未經區塊鏈網路確認
//可以在geth運行期間一直解鎖賬戶
personal.unlockAccount(eth.accounts[0],"123",0)
"enode://238dec8d985d6959f8b99e94e8d343be4a3d0f6737972531b226ea154212d3cf315b536bd3f4463d29096a6c3853ab783f2e78faeb6a787259e888d782dec88c@115.29.67.40:30303"
eth.sendTransaction({from:user1,to:user2,value:web3.toWei(3,"ether")})
挖礦命令
#若本機挖礦成功,礦工地址就會有就會有一筆收益,可以通過eth.coinbase查看
eth.coinbase
#設定礦工地址
miner.setEtherbase(eth.coinbase)
#設定礦工
miner.setEtherbase(user3)
#挖礦,開啟1個執行緒挖礦
miner.start(1)
#查看是否在挖礦
eth.mining
#結束挖礦
miner.stop()
# 挖出新區塊后,立馬停止
miner.start(1);admin.sleepBlocks(1);miner.stop();
查看交易指令
#查看本地交易池,待提交的交易
txpool.status
eth.getBlock("pending", true).transactions
#查看用戶的以太幣個數,用以太幣表示,而不是Wei
web3.fromWei(eth.getBalance(eth.accounts[1]),'ether')
#通過交易鏈接,查看交易
eth.getTransaction("0x9f5e61f3d686f793e2df6378d1633d7a9d1df8ec8c597441e1355112d102a6ce")
將區塊鏈資料同步到其它 peer 節點
當 peer 連接好了的時候,就自動完成同步了
#查看其它節點資訊
admin.peers
#查看node資訊
admin.nodeInfo
admin.nodeInfo.enode
區塊鏈中,節點是p2p模式網路
#通過admin.addPeer()添加peer節點,添加節點1
admin.addPeer("enode://917e60c31d4cac6eb1af97fd971c96f172f386d5de04fadaf01b0e1ff38c49877e4a1fcd3275659e6fd19c9fb09fc5a93a50597ff9b87d261ca216706106923b@192.168.188.133:30303")
#查看是否有其它的peer
net.peerCount
#單位換算
web3.fromWei(100000000,'ether')
#跨節點轉賬: 如果報錯可能安裝web3的版本太高
eth.sendTransaction({from:address1,to:address2,value:web3.toWei(3,"ether")})
如何驗證區塊鏈節點,同步了?
可以將BlockChain2和BlockChain3,分別在Geth的控制臺下,使用admin.addpeer()連接到Cluster節點(第一個節點),可以開啟一個節點的挖礦程式,在別的系統中,查看區塊,發現,另一臺主機也在進行同步,
如何通過產生的交易地址,來查看交易內容?
開發框架Truffle
開發框架Truffle介紹
truffle 是一個部署合約的框架,提高效率
安裝方式
1 添加 node 源
$ curl -sL https://deb.nodesource.com/setup_14.x | sudo -E bash -
2 安裝 nodejs
$ sudo apt-get install -y nodejs
3 安裝區塊鏈測驗環境
$ npm install -g ganache-cli
$ ganache-cli --version
Ganache CLI v6.12.2 (ganache-core: 2.13.2)
$ npm install -g ethereumjs-testrpc
4 安裝truffle
$ sudo npm install -g truffle
5 終端創建一個目錄
mkdir test
cd test
6 下載初始專案
truffle init
7 在contract 目錄下撰寫智能合約Say.sol
pragma solidity ^0.5.0;
contract Say {
string private content;
function set(string memory _msg) public {
content=_msg;
}
function say() public view returns(string memory ){
return content;;
}
}
~
8 增加合約部署檔案
#在目錄migrations下新建2_deploy_contracts.js(1開頭的檔案不能洗掉,否則就會報錯)
var Say = artifacts.require("./Say.sol");
module.exports = function(deployer) {
deployer.deploy(Say);
};
9 編譯合約 執行命令(應該在truffle目錄下)
truffle compile
//此時執行編譯時,
? Fetching solc version list from solc-bin. Attempt #3
卡在這卡了很久?
解決辦法:見bug
10 修改目錄下的檔案truffle-config.js 如下(host和port要根據自己的配置來定)部署合約到區塊鏈上
module.exports = {
networks:{
development:{
host:"localhost",
port:8545,
network_id:"20210821",
gas:3000000
}
}
};
11 部署前先解鎖賬號,并啟動挖礦
>personal.unlockAccount(user1)
>miner.start()
12 然后執行部署,應該是在truffle目錄下
truffle migrate
此處報錯,解決見bug5
truffle 開發 ,使用開發模式的前提是,之前一定要安裝第三步,區塊鏈測驗環境
$ truffle Develop
started at http://127.0.0.1:9545/
Accounts:
(0) 0x55cc26a61e5ed0946aee50e7895f1064ccd01da4
(1) 0x17f53146ab4ecb78fa9c9c3795ee84e77b46a7a9
(2) 0x37110b76c6951c94ced4b4d46ef99013b60652cf
(3) 0xc7910dc26d37ff4cc3b855527c4074ddb36f8942
(4) 0x70aac68de9e77ec836f431e048d287a8f9330a55
...
?? Important ?? : This mnemonic was created for you by Truffle. It is not secure.
Ensure you do not use it on production blockchains, or else you risk losing funds.
$ truffle(develop)> compile
Compiling your contracts...
===========================
> Everything is up to date, there is nothing to compile.
truffle(develop)> truffle migrate
Compiling your contracts...
===========================
> Everything is up to date, there is nothing to compile.
Starting migrations...
======================
> Network name: 'develop'
> Network id: 5777
> Block gas limit: 6721975 (0x6691b7)
1_initial_migration.js
======================
Deploying 'Migrations'
----------------------
> transaction hash: 0xf6dbd0e3400fc70664a6b60fa922377ee2b5f3ac6bb630ae20d951d05791c442
> Blocks: 0 Seconds: 0
> contract address: 0xE612CF8f9DDCCfB89D5aED08E9cDeFFb3711ABc6
> block number: 1
> block timestamp: 1630758669
> account: 0x55Cc26A61E5eD0946aEe50e7895f1064cCD01dA4
> balance: 99.999616114
> gas used: 191943 (0x2edc7)
> gas price: 2 gwei
> value sent: 0 ETH
> total cost: 0.000383886 ETH
> Saving migration to chain.
> Saving artifacts
-------------------------------------
> Total cost: 0.000383886 ETH
2_deploy_contracts.js
=====================
Deploying 'Say'
---------------
> transaction hash: 0x35fed518448b51036dd245c5f180d6af7c3e7050e5c166bff94f9360479e3ce2
> Blocks: 0 Seconds: 0
> contract address: 0x02db26E5099Ae13ad8282A82A7bD818e3030bC27
> block number: 3
> block timestamp: 1630758669
> account: 0x55Cc26A61E5eD0946aEe50e7895f1064cCD01dA4
> balance: 99.99908693
> gas used: 222254 (0x3642e)
> gas price: 2 gwei
> value sent: 0 ETH
> total cost: 0.000444508 ETH
> Saving migration to chain.
> Saving artifacts
-------------------------------------
> Total cost: 0.000444508 ETH
Summary
=======
> Total deployments: 2
> Final cost: 0.000828394 ETH
- Blocks: 0 Seconds: 0
- Saving migration to chain.
- Blocks: 0 Seconds: 0
- Saving migration to chain.
安裝nodejs
//新建一個檔案夾,然后初始化
$ mkdir nodejs && cd nodejs
$ npm init -f //此處的-f會自動給你配好組態檔
$ npm install web3@^0.20.0
//若想 安裝最新版web3 npm install web3
安裝報錯,見bug6
查看,node內嵌web3版本的方式
chenhui@ubuntu:~/privateblock/nodejs$ node
> web3.version.api
Thrown:
ReferenceError: web3 is not defined
> var Web3 = require('web3')
undefined
> var web3 = new Web3(new Web.providers.HttpProvider("http://localhost:8545"))
Thrown:
ReferenceError: Web is not defined
> var web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"))
undefined
> web3.version.api
'0.20.7'
nodejs 在命令列輸入引數
var arguments = process.argv.splice(2)
arguments[0] arguments[1]
Bug 筆記
1. Fatal: Error starting protocol stack: listen tcp :30303: bind: address already in use
ps ax | grep geth
kill -9 <pid>
2.personal.unlockAccount(user1,“12345678”)
解鎖失敗,報錯如下
GoError: Error: could not decrypt key with given password at web3.js:6357:37(47)
at native
at :1:30(4)
解決方案:可能是密碼出錯了,也可能是
嘗試新建一個用戶
eth.newAccount("123")
并將這個用戶立馬使用
personal.unlockAccount(eth.accounts[2])
輸入密碼:123
3.Error: etherbase must be explicitly specified
at web3.js:6357:37(47)
at get (web3.js:6257:66(14))
可能首次,沒有創建用戶
4.truffle compile編譯這部分,可能需要弄很久
http://www.manongjc.com/detail/19-sczhvzvgfkmlgse.html
解決方案:https://learnblockchain.cn/question/1568
將 compiler 用別的方式下載下來,放到下面的目錄~,

修改truffle-config.js中的去掉version注釋


5.報錯如下
undefined:1
b0VIM 8.1
^
SyntaxError: Unexpected token b in JSON at position 0
at JSON.parse ()
chenhui@ubuntu:~/privateblock/truffle$ truffle migrate
Compiling your contracts...
===========================
> Everything is up to date, there is nothing to compile.
Starting migrations...
======================
> Network name: 'development'
> Network id: 20210821
> Block gas limit: 4787948 (0x490eec)
1_initial_migration.js
======================
undefined:1
b0VIM 8.1
^
SyntaxError: Unexpected token b in JSON at position 0
at JSON.parse (<anonymous>)
at FS.getContractName (/usr/lib/node_modules/truffle/build/webpack:/packages/resolver/dist/lib/sources/fs.js:44:1)
at FS.require (/usr/lib/node_modules/truffle/build/webpack:/packages/resolver/dist/lib/sources/fs.js:25:1)
at /usr/lib/node_modules/truffle/build/webpack:/packages/resolver/dist/lib/resolver.js:53:1
at Array.forEach (<anonymous>)
at Resolver.require (/usr/lib/node_modules/truffle/build/webpack:/packages/resolver/dist/lib/resolver.js:52:1)
at Object.require (/usr/lib/node_modules/truffle/build/webpack:/packages/migrate/index.js:172:1)
at ResolverIntercept.require (/usr/lib/node_modules/truffle/build/webpack:/packages/migrate/ResolverIntercept.js:22:1)
at /home/chenhui/privateblock/truffle/migrations/1_initial_migration.js:1:30
at Script.runInContext (vm.js:144:12)
at Script.runInNewContext (vm.js:149:17)
at Object.file (/usr/lib/node_modules/truffle/build/webpack:/packages/require/require.js:94:1)
at Migration._load (/usr/lib/node_modules/truffle/build/webpack:/packages/migrate/Migration.js:44:1)
at processTicksAndRejections (internal/process/task_queues.js:95:5)
at Migration.run (/usr/lib/node_modules/truffle/build/webpack:/packages/migrate/Migration.js:217:1)
at Object.runMigrations (/usr/lib/node_modules/truffle/build/webpack:/packages/migrate/index.js:150:1)
Truffle v5.4.9 (core: 5.4.9)
Node v14.17.6
解決:
1_initial_migration.js 這個檔案是重要檔案,不能洗掉,洗掉就會報上面的錯誤
6:chenhui@ubuntu:~/privateblock/nodejs$ npm install web3@0.20.0
npm ERR! code ENOENT
npm ERR! syscall spawn git
npm ERR! path git
npm ERR! errno ENOENT
npm ERR! enoent Error while executing:
npm ERR! enoent undefined ls-remote -h -t https://github.com/frozeman/bignumber.js-nolookahead.git
npm ERR! enoent
npm ERR! enoent
npm ERR! enoent spawn git ENOENT
npm ERR! enoent This is related to npm not being able to find a file.
npm ERR! enoent
npm ERR! A complete log of this run can be found in:
npm ERR! /home/chenhui/.npm/_logs/2021-09-05T08_29_15_774Z-debug.log
錯誤原因,沒有安裝git
解決辦法: 用管理員權限安裝git
sudo apt install git
此錯誤好了,出現下列錯誤
chenhui@ubuntu:~/privateblock/nodejs$ npm install web3@0.20.0
npm ERR! code 128
npm ERR! Command failed: git clone --mirror -q https://github.com/frozeman/bignumber.js-nolookahead.git /home/chenhui/.npm/_cacache/tmp/git-clone-40a3a4f4/.git
npm ERR! warning: templates not found in /tmp/pacote-git-template-tmp/git-clone-921abd23
npm ERR! fatal: unable to access 'https://github.com/frozeman/bignumber.js-nolookahead.git/': GnuTLS recv error (-54): Error in the pull function.
npm ERR!
npm ERR! A complete log of this run can be found in:
npm ERR! /home/chenhui/.npm/_logs/2021-09-05T08_33_49_217Z-debug.log
錯誤原因:嘗試
git config --global url.“https://”.insteadOf git://
再進行安裝,沒有成功,再嘗試,報錯
npm ERR! Error while executing:
npm ERR! /usr/bin/git ls-remote -h -t https://github.com/frozeman/bignumber.js-nolookahead.git
npm ERR!
npm ERR! fatal: unable to access 'https://github.com/frozeman/bignumber.js-nolookahead.git/': GnuTLS recv error (-54): Error in the pull function.
npm ERR!
npm ERR! exited with error code: 128
npm ERR! A complete log of this run can be found in:
npm ERR! /root/.npm/_logs/2021-09-06T07_09_43_403Z-debug.log
執行:
git config --global url.git://github.com/.insteadOf https://github.com/
解決辦法
執行:
git config --global url.git://github.com/.insteadOf https://github.com/
結果

7.連接MetaMask報錯
報錯問題:無法獲取鏈 IC,您的 RPC URL 地址是正確的么?
原因是少了–http.port 8545 和 --http.addr “0.0.0.0”
下面是我開啟geth的命令
#!/bin/bash
nohup geth --datadir data --networkid 666 --http --http.corsdomain="*" --http.port 8545 --http.addr "0.0.0.0" --http.api db,web3,eth,debug,personal,net,miner,admin --allow-insecure-unlock --rpc.allow-unprotected-txs --port 30303 --dev --dev.period 1 2>./console.log &
連接成功圖:
注意:鏈id 為genesis.json檔案中的chainid ,而不是運行geth時的 networkid
如果上述錯誤,請確認,通過上述開啟的 geth 的引數都沒有遺漏
8.remix 部署合約上不了鏈,或者轉賬無法資料無法上鏈
解決方式:
1.將鏈id 和 網路id更換為相同的
2.把metamask卸載重新安裝
3 .增大 gas limit

9.區塊鏈編程,想通過呼叫區塊鏈上的函式時,出現了跨域問題
test.html:1
Access to XMLHttpRequest at 'http://10.69.177.223:8545/' from origin 'http://localhost:8080' has been blocked by CORS policy: Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response.
index.js:106
POST http://10.69.177.223:8545/ net::ERR_FAILED
test.html:1
Access to XMLHttpRequest at 'http://10.69.177.223:8545/' from origin 'http://localhost:8080' has been blocked by CORS policy: Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response.
index.js:106
POST http://10.69.177.223:8545/ net::ERR_FAILED
errors.js:43
Uncaught (in promise) Error: Invalid JSON RPC response: ""
at Object.InvalidResponse (errors.js:43)
at XMLHttpRequest.i.onreadystatechange (index.js:95)
錯誤原因,跨域的時候,之前只指定了http://remix.etherum.org,導致出現跨域問題, 后面將-http.corsdomain="" 改為 “”成功解決
下面是我開啟geth的命令列指令
nohup geth --datadir data --networkid 666 --ipcdisable --rpc --rpccorsdomain "*" --port 30303 --rpcport 8545 --rpcaddr "0.0.0.0" --http --http.corsdomain="*" --http.api db,web3,eth,debug,personal,net,miner,admin --vmdebug --rpcapi "db,eth,net,web3,admin,personal,miner" --allow-insecure-unlock 2>./console.log &
10.當使用idea開發java時,使用
E:\Ethereum-java>mvn web3j:generate-sources
出現下列需要等待很久
Solidity version 0.4.25 is not installed. Downloading and installing it to ~/.web3j/solc/0.4.25
解決辦法:開啟科學上網工具,等待一下就會自己下載完畢
11 . java.lang.RuntimeException: java.lang.RuntimeException: Error processing transaction request: only replay-protected (EIP-155) transactions allowed over RPC
at org.web3j.tx.Contract.deploy(Contract.java:460)
at org.web3j.tx.Contract.deploy(Contract.java:506)
at org.web3j.tx.Contract.lambda$deployRemoteCall$5(Contract.java:549)
at org.web3j.protocol.core.RemoteCall.send(RemoteCall.java:42)
at com.nwpu.eth.sol.SaySample.deploy(SaySample.java:42)
at com.nwpu.eth.sol.SaySample.main(SaySample.java:30)
解決辦法在打geth時,-加入引數--rpc.allow-unprotected-txs
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/340504.html
標籤:區塊鏈
