以太坊交互工具
Posted 七芒星实验室
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了以太坊交互工具相关的知识,希望对你有一定的参考价值。
交互工具
以太坊提供了Geth客户端用于管理API,我们可以在终端输入geth help查看其具体使用方法:
geth - the go-ethereum command line interface
Copyright 2013-2021 The go-ethereum Authors
geth [options] [command] [command options] [arguments...]
1.10.2-stable-97d11b01
account Manage accounts
attach an interactive javascript environment (node)
console an interactive JavaScript environment
db dump Dump a specific dumpconfig configuration dumpgenesis Dumps genesis configuration stdout
blockchain the preimage an RLP stream
a blockchain the preimage an RLP stream
init Bootstrap initialize a genesis js the specified JavaScript files
license Display license information
makecache Generate ethash verification (testing)
makedag Generate ethash DAG (testing)
removedb Remove blockchain state flags that have been deprecated
A commands based the Print numbers
Checks (suffers known vulnerabilities
Manage Ethereum presale wallets
commands one command
OPTIONS:
OPTIONS:
POOL OPTIONS:
TUNING OPTIONS:
OPTIONS:
CONSOLE OPTIONS:
OPTIONS:
MACHINE OPTIONS:
DEBUGGING OPTIONS:
STATS OPTIONS:
Copyright The
钱包账户相关
链数据相关
配置文件相关
数据库操作相关
节点启动主程序
杂项查询相关
使用模板
安全版本检查
geth - the go-ethereum command line interface Copyright 2013-2021 The go-ethereum Authors
geth [options] [command] [command options] [arguments...]
1.10.2-stable-97d11b01
account Manage accounts
attach an interactive JavaScript environment (node)
console an interactive JavaScript environment
db dump Dump a specific dumpconfig configuration dumpgenesis Dumps genesis configuration stdout
blockchain the preimage an RLP stream
a blockchain the preimage an RLP stream
init Bootstrap initialize a genesis js the specified JavaScript files
license Display license information
makecache Generate ethash verification (testing)
makedag Generate ethash DAG (testing)
removedb Remove blockchain state flags that have been deprecated
A commands based the Print numbers
Checks (suffers known vulnerabilities
Manage Ethereum presale wallets
commands one command
Copyright The
(
......
(
clientIdentifier = (
gitCommit = gitDate = app = flags.NewApp(gitCommit, gitDate, nodeFlags = []cli.Flag
utils.IdentityFlag,
utils.UnlockedAccountFlag,
utils.PasswordFileFlag,
utils.BootnodesFlag,
utils.DataDirFlag,
utils.AncientFlag,
utils.MinFreeDiskSpaceFlag,
utils.KeyStoreDirFlag,
......
utils.MinerNotifyFullFlag,
configFileFlag,
rpcFlags = []cli.Flag
utils.HTTPEnabledFlag,
......
utils.AllowUnprotectedTxs,
metricsFlags = []cli.Flag
utils.MetricsEnabledFlag,
......
utils.MetricsInfluxDBTagsFlag,
app.Action = geth
app.HideVersion = app.Copyright = app.Commands = []cli.Command
initCommand,
importCommand,
exportCommand,
importPreimagesCommand,
exportPreimagesCommand,
removedbCommand,
dumpCommand,
dumpGenesisCommand,
accountCommand,
walletCommand,
consoleCommand,
attachCommand,
javascriptCommand,
makecacheCommand,
makedagCommand,
versionCommand,
versionCheckCommand,
licenseCommand,
dumpConfigCommand,
dbCommand,
utils.ShowDeprecated,
snapshotCommand,
sort.Sort(cli.CommandsByName(app.Commands))
app.Flags = app.Flags = app.Flags = app.Flags = app.Flags = app.Before =
debug.Setup(ctx)
app.After =
debug.Exit()
prompt.Stdin.Close()
err := app.Run(os.Args); err !=
fmt.Fprintln(os.Stderr, err)
os.Exit(
ctx.GlobalIsSet(utils.RopstenFlag.Name):
log.Info( ctx.GlobalIsSet(utils.RinkebyFlag.Name):
log.Info( ctx.GlobalIsSet(utils.GoerliFlag.Name):
log.Info( ctx.GlobalIsSet(utils.YoloV3Flag.Name):
log.Info( ctx.GlobalIsSet(utils.DeveloperFlag.Name):
log.Info( !ctx.GlobalIsSet(utils.NetworkIdFlag.Name):
log.Info(
ctx.GlobalString(utils.SyncModeFlag.Name) != && !ctx.GlobalIsSet(utils.CacheFlag.Name) && !ctx.GlobalIsSet(utils.NetworkIdFlag.Name)
!ctx.GlobalIsSet(utils.RopstenFlag.Name) && !ctx.GlobalIsSet(utils.RinkebyFlag.Name) && !ctx.GlobalIsSet(utils.GoerliFlag.Name) && !ctx.GlobalIsSet(utils.DeveloperFlag.Name)
log.Info( ctx.GlobalSet(utils.CacheFlag.Name, strconv.Itoa(
ctx.GlobalString(utils.SyncModeFlag.Name) == && !ctx.GlobalIsSet(utils.CacheFlag.Name)
log.Info( ctx.GlobalSet(utils.CacheFlag.Name, strconv.Itoa(
utils.SetupMetrics(ctx)
metrics.CollectProcessMetrics(* time.Second)
args := ctx.Args();
fmt.Errorf(
prepare(ctx)
stack, backend := makeFullNode(ctx)
stack.Close()
startNode(ctx, stack, backend)
stack.Wait()
app.Action = geth
app.HideVersion = app.Copyright = app.Commands = []cli.Command
initCommand,
importCommand,
exportCommand,
importPreimagesCommand,
exportPreimagesCommand,
removedbCommand,
dumpCommand,
dumpGenesisCommand,
accountCommand,
walletCommand,
consoleCommand,
attachCommand,
javascriptCommand,
makecacheCommand,
makedagCommand,
versionCommand,
versionCheckCommand,
licenseCommand,
dumpConfigCommand,
dbCommand,
utils.ShowDeprecated,
snapshotCommand,
sort.Sort(cli.CommandsByName(app.Commands))
app.Flags = app.Flags = app.Flags = app.Flags = app.Flags = app.Before =
debug.Setup(ctx)
app.After =
debug.Exit()
prompt.Stdin.Close()
err := app.Run(os.Args); err !=
fmt.Fprintln(os.Stderr, err)
os.Exit(
= =
cfg := gethConfigNode: defaultNodeConfig()
file := ctx.GlobalString(configFileFlag.Name); file !=
err := loadConfig(file, &cfg); err !=
utils.Fatalf(
utils.SetNodeConfig(ctx, &cfg.Node)
scryptN, scryptP, keydir, err := cfg.Node.AccountConfig()
err !=
utils.Fatalf(
password := utils.GetPassPhraseWithList( account, err := keystore.StoreKey(keydir, password, scryptN, scryptP)
err !=
utils.Fatalf(
fmt.Printf( fmt.Printf( fmt.Printf( fmt.Printf( fmt.Printf( fmt.Printf( fmt.Printf(
_, a, err := storeNewKey(&keyStorePassphrasedir, scryptN, scryptP, a, err
keyjson, err := EncryptKey(key, auth, ks.scryptN, ks.scryptP)
err !=
err
tmpName, err := writeTemporaryKeyFile(filename, keyjson)
err !=
err
!ks.skipKeyFileVerification
_, err = ks.GetKey(key.Address, tmpName, auth)
err !=
msg := +
+
+
+
+
fmt.Errorf(msg, tmpName, err)
os.Rename(tmpName, filename)
_, a, err := storeNewKey(&keyStorePassphrasedir, scryptN, scryptP, a, err
key, err := newKey(rand)
err !=
a := accounts.Account
Address: key.Address,
URL: accounts.URLScheme: KeyStoreScheme, Path: ks.JoinPath(keyFileName(key.Address)),
err := ks.StoreKey(a.URL.Path, key, auth); err !=
zeroKey(key.PrivateKey)
key, a, err
privateKeyECDSA, err := ecdsa.GenerateKey(crypto.S256(), rand)
err !=
newKeyFromECDSA(privateKeyECDSA), *
id, err := uuid.NewRandom()
err !=
key := &Key
Id: id,
Address: crypto.PubkeyToAddress(privateKeyECDSA.PublicKey),
PrivateKey: privateKeyECDSA,
key
keyjson, err := EncryptKey(key, auth, ks.scryptN, ks.scryptP)
err !=
err
tmpName, err := writeTemporaryKeyFile(filename, keyjson)
err !=
err
!ks.skipKeyFileVerification
_, err = ks.GetKey(key.Address, tmpName, auth)
err !=
msg := +
+
+
+
+
fmt.Errorf(msg, tmpName, err)
os.Rename(tmpName, filename)
keyBytes := math.PaddedBigBytes(key.PrivateKey.D, cryptoStruct, err := EncryptDataV3(keyBytes, [] err !=
encryptedKeyJSONV3 := encryptedKeyJSONV3
hex.EncodeToString(key.Address[:]),
cryptoStruct,
key.Id.String(),
version,
json.Marshal(encryptedKeyJSONV3)
salt := _, err := io.ReadFull(rand.Reader, salt); err !=
+ err.Error())
derivedKey, err := scrypt.Key(auth, salt, scryptN, scryptR, scryptP, scryptDKLen)
err !=
CryptoJSON, err
encryptKey := derivedKey[: iv := _, err := io.ReadFull(rand.Reader, iv); err !=
+ err.Error())
cipherText, err := aesCTRXOR(encryptKey, data, iv)
err !=
CryptoJSON, err
mac := crypto.Keccak256(derivedKey[ scryptParamsJSON := scryptParamsJSON[ scryptParamsJSON[ scryptParamsJSON[ scryptParamsJSON[ scryptParamsJSON[ cipherParamsJSON := cipherparamsJSON
IV: hex.EncodeToString(iv),
cryptoStruct := CryptoJSON
Cipher: CipherText: hex.EncodeToString(cipherText),
CipherParams: cipherParamsJSON,
KDF: keyHeaderKDF,
KDFParams: scryptParamsJSON,
MAC: hex.EncodeToString(mac),
cryptoStruct,
dirPerm = err := os.MkdirAll(filepath.Dir(file), dirPerm); err !=
f, err := ioutil.TempFile(filepath.Dir(file), err !=
_, err := f.Write(content); err !=
f.Close()
os.Remove(f.Name())
f.Close()
f.Name(), !ks.skipKeyFileVerification
_, err = ks.GetKey(key.Address, tmpName, auth)
err != nil
msg := +
+
+
+
+
fmt.Errorf(msg, tmpName, err)
os.Rename(tmpName, filename)
geth account - a an existing account.
you prompted well passwords supplied via a given file.
meant scripted networks known
environments.
you gave creating a (it you able your account.
unencrypted supported.
<DATADIR>/keystore.
transfer the entire the individual therein
ethereum nodes simply copying.
your regularly.
geth command [command options] [arguments...]
Print summary existing accounts
a an existing a a geth db - Low level database operations
geth db command [command options] [arguments...]
inspect Inspect the storage size for each type of data in the database
stats Print leveldb statistics
compact Compact leveldb database. WARNING: May take a very long time
get the a a ( put the a ( dumptrie the a given trie
geth wallet -
geth wallet import /path/to/my/presale.wallet
your password imports your ether presale account.
plaintext.
geth wallet command [command options] [arguments...]
ACCOUNT import Import Ethereum presale wallet
--help, -h show help
ubuntu@ubuntu:~/geth-linux-amd64$
搭私有链
暂略~
文末小结
本篇文章以以太坊公链交互工具Geth为例介绍了公链交互工具命令参数的解析与执行流程,同时以Geth为例对其使用进行了简易演示,后面我们将对公链接口设计进行分析~
记 通过ganache与以太坊Dapp实现交互
通过ganache与以太坊Dapp实现交互
参考来源:以太坊Dapp开发教程
我的环境准备:
ubuntu-20.04.4,nodejs(v16.14.0),npm(v8.3.1)
安装ganache
ps:视频中是ganache-cli,看github介绍应该是ganache
sudo npm install ganache --global
ps:一些报错,因为虚拟机是新安装的,所以会有很多命令没有,可以跳过这一块
根据提示执行npm install -g npm@8.5.2
报错没有make命令,执行
sudo apt-get install gcc automake autoconf libtool make -y
报错g++: Command not found,执行
sudo apt-get install build-essential
执行ganache-cli
ps:我安装nodejs参考的教程
报错:ganache-cli: command not found
原因:没有设置全局变量
解决:
在/usr/bin 的目录下输入sudo ln -s /usr/local/node/bin/ganache-cli ganache-cli
运行ganache-cli输出一下结果:
ganache v7.0.2 (@ganache/cli: 0.1.3, @ganache/core: 0.1.3)
Starting RPC server
//默认生成10个账户
Available Accounts
==================
(0) 0xa6AF4787B11B4f05e77f53fE0D6384Bbb17aF467 (1000 ETH)
(1) 0xc77ca72fac71088D5AFf1786DA2528EfD84B5C1e (1000 ETH)
(2) 0xF85541DBF0fA61e314e7A6960B58caC93D98d881 (1000 ETH)
(3) 0x61aBB6AfC93035Fb05EFe34bC9c255Fd75f334e9 (1000 ETH)
(4) 0x8EF8EA235646d0c02F60ef4b14b24136CD6FE222 (1000 ETH)
(5) 0xe82fD6Abdf21bEa708879810bb80bB2B5a25fC14 (1000 ETH)
(6) 0x80BD5be7D1847092E8e25166483F6f89B0517966 (1000 ETH)
(7) 0xf6018FBfd5D496508b80B5Ace4f07e69549B835a (1000 ETH)
(8) 0x70EBFd720739e0C2a4c1384c5dcC2Be74595fEA1 (1000 ETH)
(9) 0x45250D5aC35391f90AeCddDB22516528Fd4F3de4 (1000 ETH)
Private Keys
==================
(0) 0x0348895a76b76a393dcd1500e0f29a6a8382dcb3f5ef5af52e7d81552bfeab2d
(1) 0x44942b204c402bbe83a2ff6e16c281fa19cc12f64e05bfa2fd928dee2d4f829c
(2) 0xa0e9decac315f37bd5f97e27d451001b180c1b520cbce4cf97f5caa2a95a44bc
(3) 0xe7e67fa01f524618a6de82090787800a4d6cc3d76b07ecce409bb7d99b089e75
(4) 0x73c6d0f082ff6eb427c0a8897c245ffe151e7e850116971a14abbd8227e4bc5e
(5) 0x5b7e6aaf6e85a8de5f319c9462afbe2958c64fbbcf193d9471db3e1692cdd594
(6) 0x28dc84f77a4e4bc5f231a29ab5472f25aaa70a4843cf31088ccbdc164bcdca4a
(7) 0x17373c3c42cd4aee48e6bc7d32953adddbc8384496808274ceca57b95c949fb4
(8) 0x68ebf31159f888326866ac77b669f50a1df7f58ee4957ee1aa03feb0236df84a
(9) 0x99a5e7dc8b95424db026c2af1eb87482b2760e814155a670cdb2e0c1af5e4164
HD Wallet
==================
Mnemonic: various harbor poverty abandon mosquito sand excite devote juice manual people dry
Base HD Path: m/44'/60'/0'/0/account_index
Default Gas Price
==================
2000000000
BlockGas Limit
==================
30000000
Call Gas Limit
==================
50000000
Chain Id
==================
1337
RPC Listening on 127.0.0.1:8545
^C
Received shutdown signal: SIGINT
Shutting down…
Server has been shut down
ganache-cli 的使用
创建新的文件夹,在那下面安装web3
sudo npm install web3 --unsafe-perm=true --allow-root
//如果没有换源则
sudo npm install web3 --unsafe-perm=true --allow-root --registry=https://registry.npm.taobao.org
如果没有出现node_modules,可以尝试npm init,npm install
windows10下安装web3
直接npm install web3
会报错
- 需要先安装cnpm
npm install -g cnpm --registry=https://registry.npm.taobao.org
- 再运行
cnpm install node-gyp
- 再
cnpm install web3
安装好后可以用npm view web3查看web3版本
测试web3
尝试能否连接到web3:vim test.js
内容是:
var Web3 = require('web3');
var web3 = new Web3(new Web3.providers.HttpProvider('http://localhost:8545'));
console.log(web3.version);
用node test.js运行,结果:
内容改为:
var Web3 = require('web3');
var web3 = new Web3(new Web3.providers.HttpProvider('http://localhost:8545'));
console.log(web3.version);
web3.eth.getAccounts().then(console.log)
在另一个终端启动ganache-cli
运行node test.js
不运行ganache-cli,直接node test.js会报错
使用web3js和区块链进行交互
创建新目录
mkdir dapp
安装express
sudo npm install express -g
sudo npm install -g express-generator
我的版本号
创建工程
express -e MyDapp
//进入目录
cd MyDapp/
安装
npm install
启动工程
npm start
输入 127.0.0.1:3000 (8545是区块链的端口)
安装web3
npm install web3 -save
进入到routes文件夹修改index.js,修改内容为
var express = require('express');
var router = express.Router();
var Web3 = require('web3');
var web3 = new Web3(new Web3.providers.HttpProvider('http://localhost:8545'));
web3.eth.getAccounts().then(console.log);//获取账户
/* GET home page. */
router.get('/', function(req, res, next)
web3.eth.getAccounts().then(function(accounts)
var account = accounts[0];
web3.eth.getBalance(account).then(function(balance)
var amount = web3.utils.fromWei(balance,'ether');
res.render('index',account: account,balance: amount);
);
);
);
module.exports = router;
修改app.js
var ejs = require('ejs');
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.engine('.html',ejs.__express);//修改引擎为html
app.set('view engine', 'html');
修改以下代码
在view目录下新建index.html
<!DOCTYPE html>
<html>
<head>
<title>账户余额</title>
<link rel='stylesheet' href='/stylesheets/style.css' />
</head>
<body>
<h1>账户是: <%= account %></h1>
<h1>余额是: <%= balance %></h1>
</body>
</html>
开另一个终端,启动ganache-cli
再启动项目npm install
浏览器输入127.0.0.1:3000可以得到ganache与web3交互的过程
至此,视频04结束。
结下来,需通过web3.js来调用我们写的这个合约
接:以太坊智能合约部署调用
以上是关于以太坊交互工具的主要内容,如果未能解决你的问题,请参考以下文章