-
Notifications
You must be signed in to change notification settings - Fork 1
/
ethereum.solidity.xml
1330 lines (1185 loc) · 40.7 KB
/
ethereum.solidity.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE book PUBLIC "-//OASIS//DTD DocBook XML V5.0//EN" "/usr/share/xml/docbook/schema/dtd/5.0/docbook.dtd" [
<!ENTITY article.author.xml SYSTEM "../common/article.author.xml">
<!ENTITY book.info.legalnotice.xml SYSTEM "../common/book.info.legalnotice.xml">
<!ENTITY book.info.abstract.xml SYSTEM "../common/book.info.abstract.xml">
]>
<article xml:base="http://netkiller.github.io/journal/" xmlns="http://docbook.org/ns/docbook"
xml:lang="zh-cn">
<articleinfo>
<title>以太坊智能合约开发入门</title>
<subtitle>本文作者最近在找工作,有意向致电 13113668890</subtitle>
&article.author.xml;
&book.info.legalnotice.xml;
<abstract>
<para>本文采用碎片化写作,原文会不定期更新,请尽量阅读原文。</para>
<para>
<ulink url="http://www.netkiller.cn/journal/ethereum.solidity.html">http://www.netkiller.cn/journal/ethereum.solidity.html</ulink>
</para>
</abstract>
&book.info.abstract.xml;
<keywordset>
<keyword>ethereum</keyword>
<keyword>geth</keyword>
<keyword>browser-solidity</keyword>
<keyword>solidity</keyword>
</keywordset>
<pubdate>$Date$</pubdate>
<release>$Id$</release>
</articleinfo>
<section id="truffle">
<title>Truffle</title>
<para>Truffle 是 solidity 开发框架</para>
<section id="truffle.setup">
<title>安装 Truffle</title>
<screen>
<![CDATA[
# 安装 Nodejs
curl -sL https://deb.nodesource.com/setup_9.x | sudo -E bash -
sudo apt-get install -y nodejs
# 安装truffle
sudo npm install -g truffle
# 安装testrpc
sudo npm install -g ethereumjs-testrpc
]]>
</screen>
</section>
<section id="truffle.init">
<title>创建项目</title>
<screen>
<![CDATA[
cd ~/ethereum
mkdir truffle-project
cd truffle-project
truffle init
]]>
</screen>
<para>操作演示</para>
<screen>
<![CDATA[
neo@netkiller ~/ethereum/truffle-project % truffle init
Downloading...
Unpacking...
Setting up...
Unbox successful. Sweet!
Commands:
Compile: truffle compile
Migrate: truffle migrate
Test contracts: truffle test
neo@netkiller ~/ethereum/truffle-project % tree
.
|-- contracts
| `-- Migrations.sol
|-- migrations
| `-- 1_initial_migration.js
|-- test
|-- truffle-config.js
`-- truffle.js
3 directories, 4 files
]]>
</screen>
</section>
<section id="truffle.js">
<title>配置 Truffle</title>
<para>打开文件 truffle.js </para>
<programlisting>
<![CDATA[
module.exports = {
// See <http://truffleframework.com/docs/advanced/configuration>
// to customize your Truffle configuration!
};
]]>
</programlisting>
<para>修改为</para>
<screen>
<![CDATA[
module.exports = {
// See <http://truffleframework.com/docs/advanced/configuration>
// to customize your Truffle configuration!
networks: {
development: {
host: "localhost",
port: 8545,
network_id: "*" // Match any network id
}
}
};
]]>
</screen>
</section>
<section id="truffle.compile">
<title>编译智能合约</title>
<screen>
<![CDATA[
neo@netkiller ~/ethereum/truffle-project % truffle compile
Compiling ./contracts/Migrations.sol...
Writing artifacts to ./build/contracts
]]>
</screen>
<para>truffle默认只会编译最后一次修改过的合约文件, 这是为了减少比重复编译。"--all"选项,可以强制编译所有文件。</para>
<para>编译结果</para>
<screen>
<![CDATA[
neo@netkiller ~/ethereum/truffle-project % find build
build
build/contracts
build/contracts/Migrations.json
]]>
</screen>
</section>
<section id="truffle.migrate">
<title>migrate</title>
<screen>
<![CDATA[
neo@netkiller ~/ethereum/truffle-project % truffle migrate
Using network 'development'.
Network up to date.
]]>
</screen>
</section>
<section id="truffle.deploy">
<title>部署智能合约</title>
<screen>
<![CDATA[
neo@netkiller ~/ethereum/truffle-project % truffle deploy
Using network 'development'.
Network up to date.
]]>
</screen>
</section>
<section id="truffle.develop">
<title>开发环境</title>
<para>truffle 自带一个开发环境</para>
<screen>
<![CDATA[
neo@netkiller ~/ethereum/truffle-project % truffle develop
Truffle Develop started at http://localhost:9545/
Accounts:
(0) 0x627306090abab3a6e1400e9345bc60c78a8bef57
(1) 0xf17f52151ebef6c7334fad080c5704d77216b732
(2) 0xc5fdf4076b8f3a5357c5e395ab970b5b54098fef
(3) 0x821aea9a577a9b44299b9c15c88cf3087f3b5544
(4) 0x0d1d4e623d10f9fba5db95830f7d3839406c6af2
(5) 0x2932b7a2355d6fecc4b5c0b6bd44cc31df247a2e
(6) 0x2191ef87e392377ec08e7c08eb105ef5448eced5
(7) 0x0f4f2ac550a1b4e2280d04c21cea7ebd822934b5
(8) 0x6330a553fc93768f612722bb8c2ec78ac90b3bbc
(9) 0x5aeda56215b167893e80b4fe645ba6d5bab767de
Private Keys:
(0) c87509a1c067bbde78beb793e6fa76530b6382a4c0241e5e4a9ec0a0f44dc0d3
(1) ae6ae8e5ccbfb04590405997ee2d52d2b330726137b875053c36d94e974d162f
(2) 0dbbe8e4ae425a6d2687f1a7e3ba17bc98c673636790f1b8ad91193c05875ef1
(3) c88b703fb08cbea894b6aeff5a544fb92e78a18e19814cd85da83b71f772aa6c
(4) 388c684f0ba1ef5017716adb5d21a053ea8e90277d0868337519f97bede61418
(5) 659cbb0e2411a44db63778987b1e22153c086a95eb6b18bdf89de078917abc63
(6) 82d052c865f5763aad42add438569276c00d3d88a2d062d36b2bae914d58b8c8
(7) aa3680d5d48a8283413f7a108367c7299ca73f553735860a87b08f39395618b7
(8) 0f62d96d6675f32685bbdb8ac13cda7c23436f63efbb9d07700d8669ff12b7c4
(9) 8d5366123cb560bb606379f90a0bfd4769eecc0557f1b362dcae9012b548b1e5
Mnemonic: candy maple cake sugar pudding cream honey rich smooth crumble sweet treat
truffle(develop)>
]]>
</screen>
<para>truffle develop 的作用于 testrpc 类似。</para>
<screen>
<![CDATA[
neo@netkiller ~/ethereum/truffle-project % testrpc
EthereumJS TestRPC v6.0.3 (ganache-core: 2.0.2)
Available Accounts
==================
(0) 0xb5fd43ee8fa5ce1db9a30a25ba385ee3bfc72966
(1) 0xf5a732345734e1f0f49cbadb145a20d1e1a44b95
(2) 0x834fcd8c55fdf21fd14c82e9a1ef5d3636a2fed6
(3) 0x5aa4d047d85727309d3ca653c83c3bb0ecd18903
(4) 0xb4db2dede86f4539e56ac4438f6e36f09c307e46
(5) 0x8da382b1a10ab2f1dc149e19fda228a07c78935c
(6) 0xb290297e89b52713548ff93e5fc23bc3c4183dde
(7) 0x546183289bd4d9d33a3aee0ee663c0729926e583
(8) 0xca58321e442533b7f827e6e8976e1905acd15214
(9) 0xe2c0b336bbb03564204e15a2cb7744564a53efcc
Private Keys
==================
(0) ff32f7a06e2fb26b51a745c1e428c60df92c0f9bb3301b19a5b7e0cdfaae521a
(1) cdbfe40321b6ade8a246748df1c48a738b8a531aee4d1f60a45bfd7f941e0064
(2) 7092117c2d7832980945e18645a60a1ed0e59261d040749f8b5202c2fc653d74
(3) f329657c9ad808e9f794a7462a1a9c276266343d5ced263ab618b6a19d6857c1
(4) 1221766592618add3a57ab109f00efcc70867dd8a9b10a0f7ea75c2b619edfc3
(5) c27005d6c3581193124c84766cc0b1cc318cb201b7d00b1035f4a4c7767ba790
(6) 6b7f43dca1dcc00203b751191096bb0602e17a9a94dcee8b846329efa703cea9
(7) 41be5971d71935bc88c3cf8aefd78ed3188c8721b7134cda3b25d353faf05d4f
(8) bd4c9d512a4f2da2cdcd9e4f89c049e3e7ac81bf57a05369997c2f13e793bebb
(9) 04196d803f743cc1fd021e7d02d5a552f14ab9826ccd4d4b265ff96c45169d2c
HD Wallet
==================
Mnemonic: confirm shift cable melody caught swing erode language spend victory conduct van
Base HD Path: m/44'/60'/0'/0/{account_index}
Listening on localhost:8545
]]>
</screen>
</section>
</section>
<section id="browser-solidity">
<title>browser-solidity</title>
<para>在线使用 browser-solidity</para>
<ulink url="https://ethereum.github.io/browser-solidity/">https://ethereum.github.io/browser-solidity/</ulink>
<ulink url="https://remix.ethereum.org/">https://remix.ethereum.org/</ulink>
<para>国内网络有时不给力,建议将 Remix 安装到本地目录。</para>
<section id="remix">
<title>将 Remix(browser-solidity) 安装到本地</title>
<para>共享合约目录</para>
<screen>
<![CDATA[
npm install -g remixd
remixd -S "/home/ethereum/codebase/blocks/contracts"
]]>
</screen>
<para>安装 browser-solidity </para>
<screen>
<![CDATA[
git clone https://github.com/ethereum/browser-solidity
cd browser-solidity
npm install
npm run prepublish
sudo chown -R $USER:$(id -gn $USER) /home/neo/.config
npm start
]]>
</screen>
<para>
启动后浏览器中输入
<ulink url="http://localhost:8080">http://localhost:8080</ulink>
可以看到 Remix 界面
</para>
<note>
<title>Web3 Provider</title>
<para>Remix 提供三种运行环境,常用的有 JavaScript VM 和 Web3 Provider (连接到 --rpc
--rpcaddr="0.0.0.0" --rpccorsdomain "*" --rpcport 8545)</para>
<para>Web3 Provider 方式需要解锁账号和启动挖矿</para>
<screen>
<![CDATA[
> personal.unlockAccount(eth.accounts[0],"");
> miner.start(2); admin.sleepBlocks(1); miner.stop();
]]>
</screen>
</note>
</section>
</section>
<section id="solc">
<title>使用 solc 编译 *.sol 代码</title>
<screen>
<![CDATA[
neo@netkiller ~/ethereum/solidity % solc --bin --abi --optimize -o ./output helloworld.sol
neo@netkiller ~/ethereum/solidity % find output
output
output/HelloWorld.bin
output/HelloWorld.abi
]]>
</screen>
</section>
<section id="solidity">
<title>智能合约语言 Solidity</title>
<para>Solidity 是什么?Solidity是以太坊智能合约的编程语言。</para>
<section id="solidity.Getting.Started">
<title>智能合约入门演示</title>
<para>这里我们先做一个 Helloword 演示,让你初步对智能合约有一个大概的认识。</para>
<tip>
<para>需要注意的是,你在网上会看到很多例子,对照这例子一步一步操作,始终无法成功,这根Solidity的版本有很大关系。</para>
</tip>
<para>将下面代码粘贴到 </para>
<programlisting>
<![CDATA[
pragma solidity ^0.4.19;
contract HelloWorld
{
string tmp;
function HelloWorld() public
{
}
function get() public constant returns (string)
{
return tmp;
}
function set(string _tmp) public
{
tmp = _tmp;
}
}
]]>
</programlisting>
<para>Compile - Details - WEB3DEPLOY</para>
<programlisting>
<![CDATA[
var helloworldContract = web3.eth.contract([{"constant":false,"inputs":[{"name":"_tmp","type":"string"}],"name":"set","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"get","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"inputs":[],"payable":false,"stateMutability":"nonpayable","type":"constructor"}]);
var helloworld = helloworldContract.new(
{
from: web3.eth.accounts[0],
data: '0x6060604052341561000f57600080fd5b6102e38061001e6000396000f30060606040526004361061004c576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff1680634ed3885e146100515780636d4ce63c146100ae575b600080fd5b341561005c57600080fd5b6100ac600480803590602001908201803590602001908080601f0160208091040260200160405190810160405280939291908181526020018383808284378201915050505050509190505061013c565b005b34156100b957600080fd5b6100c1610156565b6040518080602001828103825283818151815260200191508051906020019080838360005b838110156101015780820151818401526020810190506100e6565b50505050905090810190601f16801561012e5780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b80600090805190602001906101529291906101fe565b5050565b61015e61027e565b60008054600181600116156101000203166002900480601f0160208091040260200160405190810160405280929190818152602001828054600181600116156101000203166002900480156101f45780601f106101c9576101008083540402835291602001916101f4565b820191906000526020600020905b8154815290600101906020018083116101d757829003601f168201915b5050505050905090565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f1061023f57805160ff191683800117855561026d565b8280016001018555821561026d579182015b8281111561026c578251825591602001919060010190610251565b5b50905061027a9190610292565b5090565b602060405190810160405280600081525090565b6102b491905b808211156102b0576000816000905550600101610298565b5090565b905600a165627a7a72305820ea826c30d131f20a4d3a8e3fb059ffa95f4c222a5b099029750e4c1937b46e5b0029',
gas: '4700000'
}, function (e, contract){
console.log(e, contract);
if (typeof contract.address !== 'undefined') {
console.log('Contract mined! address: ' + contract.address + ' transactionHash: ' + contract.transactionHash);
}
})
]]>
</programlisting>
<para>部署智能合约需要消耗 gas 所以你要先解锁账号。</para>
<screen>
<![CDATA[
> personal.unlockAccount("0x83fda0ba7e6cfa8d7319d78fa0e6b753a2bcb5a6", "", 300)
true
]]>
</screen>
<screen>
<![CDATA[
> var helloworldContract = web3.eth.contract([{"constant":false,"inputs":[{"name":"_tmp","type":"string"}],"name":"set","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"get","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"inputs":[],"payable":false,"stateMutability":"nonpayable","type":"constructor"}]);
undefined
> var helloworld = helloworldContract.new(
... {
...... from: web3.eth.accounts[0],
...... data: '0x6060604052341561000f57600080fd5b6102e38061001e6000396000f30060606040526004361061004c576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff1680634ed3885e146100515780636d4ce63c146100ae575b600080fd5b341561005c57600080fd5b6100ac600480803590602001908201803590602001908080601f0160208091040260200160405190810160405280939291908181526020018383808284378201915050505050509190505061013c565b005b34156100b957600080fd5b6100c1610156565b6040518080602001828103825283818151815260200191508051906020019080838360005b838110156101015780820151818401526020810190506100e6565b50505050905090810190601f16801561012e5780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b80600090805190602001906101529291906101fe565b5050565b61015e61027e565b60008054600181600116156101000203166002900480601f0160208091040260200160405190810160405280929190818152602001828054600181600116156101000203166002900480156101f45780601f106101c9576101008083540402835291602001916101f4565b820191906000526020600020905b8154815290600101906020018083116101d757829003601f168201915b5050505050905090565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f1061023f57805160ff191683800117855561026d565b8280016001018555821561026d579182015b8281111561026c578251825591602001919060010190610251565b5b50905061027a9190610292565b5090565b602060405190810160405280600081525090565b6102b491905b808211156102b0576000816000905550600101610298565b5090565b905600a165627a7a72305820ea826c30d131f20a4d3a8e3fb059ffa95f4c222a5b099029750e4c1937b46e5b0029',
...... gas: '4700000'
...... }, function (e, contract){
...... console.log(e, contract);
...... if (typeof contract.address !== 'undefined') {
......... console.log('Contract mined! address: ' + contract.address + ' transactionHash: ' + contract.transactionHash);
......... }
...... })
null [object Object]
undefined
]]>
</screen>
<para>helloworld 智能合约已经创建完毕</para>
<screen>
<![CDATA[
> helloworld
{
abi: [{
constant: false,
inputs: [{...}],
name: "set",
outputs: [],
payable: false,
stateMutability: "nonpayable",
type: "function"
}, {
constant: true,
inputs: [],
name: "get",
outputs: [{...}],
payable: false,
stateMutability: "view",
type: "function"
}, {
inputs: [],
payable: false,
stateMutability: "nonpayable",
type: "constructor"
}],
address: undefined,
transactionHash: "0x466c9ad9db8f37ed5b65bc261210da92f51364ebab1dcbd3759bfc3e16ad6502"
}
]]>
</screen>
</section>
<section id="solidity.type.public">
<title>修饰符</title>
<screen>
<![CDATA[
public : 函数可见性
payable :可支付的函数修饰符,没有该修饰符无法接受转账操作。
msg.value :执行合约时,转账的eth数量,以wei为单位。
msg.sender : 执行合约的地址
]]>
</screen>
</section>
<section id="solidity.type">
<title>数据类型</title>
<literallayout>
<![CDATA[
uint 无符号整形(256bits 无符号整数)
string 字符串类型
]]>
</literallayout>
<section>
<title>数组</title>
<programlisting>
<![CDATA[
//创建一个memory的数组
uint[] memory a = new uint[](7);
uint[] x = [uint(1), 3, 4];
]]>
</programlisting>
</section>
<section id="solidity.enum">
<title>枚举类型</title>
<programlisting>
<![CDATA[
pragma solidity ^0.4.0;
contract Purchase {
enum State { Created, Locked, Inactive } // Enum
}
]]>
</programlisting>
</section>
<section id="solidity.struct">
<title>结构体</title>
<para>定义结构体</para>
<screen>
<![CDATA[
struct Voter {
uint weight; // weight is accumulated by delegation
bool voted; // if true, that person already voted
address delegate; // person delegated to
uint vote; // index of the voted proposal
}
// This is a type for a single proposal.
struct Proposal {
bytes32 name; // short name (up to 32 bytes)
uint voteCount; // number of accumulated votes
}
]]>
</screen>
</section>
<section>
<title>address</title>
<screen>
<![CDATA[
address public minter;
]]>
</screen>
<section>
<title>payable</title>
</section>
<section>
<title>.value()</title>
</section>
<section>
<title>.gas()</title>
</section>
</section>
</section>
<section id="solidity.variable">
<title>变量</title>
<programlisting>
<![CDATA[
address public minter;
string name;
int num;
uint constant x = 32**22 + 8;
string constant text = "abc";
bytes32 constant myHash = keccak256("abc");
uint256 ticket = 1 ether;
]]>
</programlisting>
<para>变量赋值</para>
<programlisting>
<![CDATA[
pragma solidity ^0.4.19;
contract C {
uint[] data;
function f() public view returns (uint, bool, uint) {
return (7, true, 2);
}
function g() public {
// 声明和分配变量。 明确指定类型是不可能的。
var (x, b, y) = f();
// 分配给一个预先存在的变量。
(x, y) = (2, 7);
// 互换值的常用技巧对于非价值存储类型不起作用。
(x, y) = (y, x);
// 组件可以省略(也可以用于变量声明)。
// 如果元组以空组件结束,其余的值将被丢弃。
(data.length,) = f(); // 设置长度为 7
// 在左边也可以做同样的事情。
(,data[3]) = f(); // Sets data[3] to 2
// 组件只能在作业的左侧排除,但有一个例外:
(x,) = (1,);
// (1,) 是指定1元组元的唯一方法,因为(1)等于1。
}
}
]]>
</programlisting>
</section>
<section id="solidity.function">
<title>函数</title>
<section>
<title>构造方法</title>
<para>构造方法的定义是 contract 与 function 相同</para>
<programlisting>
<![CDATA[
pragma solidity ^0.4.18;
contract MyContractByNetkiller {
/* Constructor */
function MyContractByNetkiller() public{
}
}
]]>
</programlisting>
</section>
<section>
<title>定义函数</title>
<para>没有返回值</para>
<programlisting>
<![CDATA[
function setName(string _name) public{
name = _name;
}
]]>
</programlisting>
</section>
<section>
<title>函数返回值</title>
<para>有返回值</para>
<programlisting>
<![CDATA[
function getName() public view returns(string){
return name;
}
]]>
</programlisting>
</section>
<section id="solidity.func.param">
<title>参数传递</title>
<para>除了 f(2,3) 这样传递参数,还可以使用类似字典或Map的方式 f({value: 2, key: 3});</para>
<programlisting>
<![CDATA[
pragma solidity ^0.4.0;
contract C {
function f(uint key, uint value) {
// ...
}
function g() {
// named arguments
f({value: 2, key: 3});
}
}
]]>
</programlisting>
</section>
<section>
<title>函数的例子</title>
<para>完整的例子</para>
<programlisting>
<![CDATA[
pragma solidity ^0.4.18;
contract MyContractByNetkiller {
/* Constructor */
string name;
int num;
function MyContractByNetkiller() public{
name = "default";
num = 1;
}
function setName(string _name) public{
name = _name;
}
function getName() public view returns(string){
return name;
}
function setNum(int n) public{
num = n;
}
function addNum(int m) public view returns(int res){
res = m + num;
}
}
]]>
</programlisting>
</section>
<section id="">
<title>Fallback function</title>
<programlisting>
<![CDATA[
]]>
</programlisting>
</section>
<section id="solidity.modifier">
<title>modifier</title>
<para>modifier 可以理解为 function 的触发器,或者理解为 hook。执行 function的时候会首先运行 modifier</para>
<para>_; 表示执行 modifier 完成所有命令后,继续运行 function 内的逻辑。</para>
<screen>
<![CDATA[
pragma solidity ^0.4.11;
contract owned {
function owned() { owner = msg.sender; }
address owner;
uint price;
mapping (address => bool) registeredAddresses;
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function changePrice(uint _price) onlyOwner {
price = _price;
}
function close() onlyOwner {
selfdestruct(owner);
}
}
]]>
</screen>
</section>
</section>
<section id="solidity.event">
<title>事件</title>
<programlisting>
<![CDATA[
event Sent(address from, address to, uint amount);
]]>
</programlisting>
</section>
<section id="solidity.oop">
<title>面向兑奖编程</title>
<section id="solidity.is">
<title>继承</title>
<para>例子 mortal 继承 owned</para>
<programlisting>
<![CDATA[
pragma solidity ^0.4.11;
contract owned {
function owned() { owner = msg.sender; }
address owner;
modifier onlyOwner {
require(msg.sender == owner);
_;
}
}
contract mortal is owned {
function close() onlyOwner {
selfdestruct(owner);
}
}
]]>
</programlisting>
</section>
</section>
</section>
<section id="web3j">
<title>Jave Client</title>
<para>
官方网站
<ulink url="https://web3j.io">https://web3j.io</ulink>
</para>
<para>Java 客户端与 Server 之间采用json-rpc协议连接。</para>
<section id="web3j.command.line.tools">
<title>安装命令行工具</title>
<para>web3j 命令用于将 sol 合约文件转换为 java 文件。</para>
<section>
<title>Mac OS</title>
<screen>
<![CDATA[
brew tap web3j/web3j
brew install web3j
neo@MacBook-Pro ~ % web3j
_ _____ _ _
| | |____ (_) (_)
__ _____| |__ / /_ _ ___
\ \ /\ / / _ \ '_ \ \ \ | | | / _ \
\ V V / __/ |_) |.___/ / | _ | || (_) |
\_/\_/ \___|_.__/ \____/| |(_)|_| \___/
_/ |
|__/
Usage: web3j version|wallet|solidity ...
]]>
</screen>
</section>
<section>
<title>二进制包安装</title>
<para>
下载二进制文件
<ulink url="https://github.com/web3j/web3j/releases">https://github.com/web3j/web3j/releases</ulink>
</para>
<screen>
<![CDATA[
wget https://github.com/web3j/web3j/releases/download/v3.2.0/web3j-3.2.0.zip
unzip web3j-3.2.0.zip
$ ./web3j-3.2.0/bin/web3j
_ _____ _ _
| | |____ (_) (_)
__ _____| |__ / /_ _ ___
\ \ /\ / / _ \ '_ \ \ \ | | | / _ \
\ V V / __/ |_) |.___/ / | _ | || (_) |
\_/\_/ \___|_.__/ \____/| |(_)|_| \___/
_/ |
|__/
Usage: web3j version|wallet|solidity ...
]]>
</screen>
</section>
</section>
<section id="web3j.geth">
<title>启动以太坊</title>
<para>首先启动服务</para>
<screen>
<![CDATA[
neo@netkiller ~ % geth --networkid 123456 --rpc --rpcaddr="0.0.0.0" --rpccorsdomain "*" --nodiscover
INFO [02-01|23:35:12] Starting peer-to-peer node instance=Geth/v1.7.3-stable-4bb3c89d/linux-amd64/go1.9.1
INFO [02-01|23:35:12] Allocated cache and file handles database=/home/neo/.ethereum/geth/chaindata cache=128 handles=1024
INFO [02-01|23:35:12] Initialised chain configuration config="{ChainID: 15 Homestead: 0 DAO: <nil> DAOSupport: false EIP150: <nil> EIP155: 0 EIP158: 0 Byzantium: <nil> Engine: unknown}"
INFO [02-01|23:35:12] Disk storage enabled for ethash caches dir=/home/neo/.ethereum/geth/ethash count=3
INFO [02-01|23:35:12] Disk storage enabled for ethash DAGs dir=/home/neo/.ethash count=2
INFO [02-01|23:35:12] Initialising Ethereum protocol versions="[63 62]" network=123456
INFO [02-01|23:35:12] Loaded most recent local header number=719 hash=61330b…82786e td=108754979
INFO [02-01|23:35:12] Loaded most recent local full block number=719 hash=61330b…82786e td=108754979
INFO [02-01|23:35:12] Loaded most recent local fast block number=719 hash=61330b…82786e td=108754979
INFO [02-01|23:35:12] Loaded local transaction journal transactions=0 dropped=0
INFO [02-01|23:35:12] Regenerated local transaction journal transactions=0 accounts=0
WARN [02-01|23:35:12] Blockchain not empty, fast sync disabled
INFO [02-01|23:35:12] Starting P2P networking
INFO [02-01|23:35:12] RLPx listener up self="enode://9f6490ffb5236f2ddc5710ae73d47c740e0a3644bbd2d67029cf4a6c4693d2f470b642fd2cc3507f7e851df60aaeb730a1270b7a477f91ec5b6b17a8a4b40527@[::]:30303?discport=0"
INFO [02-01|23:35:12] IPC endpoint opened: /home/neo/.ethereum/geth.ipc
INFO [02-01|23:35:12] HTTP endpoint opened: http://0.0.0.0:8545
INFO [02-01|23:35:15] Mapped network port proto=tcp extport=30303 intport=30303 interface="UPNP IGDv1-IP1"
]]>
</screen>
<para>Web3j 将使用这个地址连接 HTTP endpoint opened:
http://your_ip_address:8545</para>
</section>
<section id="web3j.pom.xml">
<title>Maven pom.xml 文件</title>
<screen>
<![CDATA[
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>cn.netkiller</groupId>
<artifactId>ethereum</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>ethereum</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.web3j</groupId>
<artifactId>core</artifactId>
<version>3.2.0</version>
</dependency>
</dependencies>
</project>
]]>
</screen>
</section>
<section id="web3j.type">
<title>Java 与 Solidity 数据类型映射关系</title>
<screen>
<![CDATA[
boolean -> bool
BigInteger -> uint/int
byte[] -> bytes
String -> string and address types
List<> -> dynamic/static array
]]>
</screen>
</section>
<section id="web3j.connect">
<title>连接到服务器获取版本号</title>
<programlisting>
<![CDATA[
package cn.netkiller.ethereum;
import java.io.IOException;
import org.web3j.protocol.Web3j;
import org.web3j.protocol.core.methods.response.Web3ClientVersion;
import org.web3j.protocol.http.HttpService;
public class Web3JClient {
// TODO Auto-generated method stub
public static void main(String[] args) {
String url = "http://172.16.0.1:8545/";
Web3j web3j = Web3j.build(new HttpService(url)); // defaults to http://localhost:8545/
try {
Web3ClientVersion web3ClientVersion = web3j.web3ClientVersion().send();
String clientVersion = web3ClientVersion.getWeb3ClientVersion();
System.out.println(clientVersion);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
]]>
</programlisting>
<para>运行结果</para>
<screen>
<![CDATA[
Geth/v1.7.3-stable-4bb3c89d/linux-amd64/go1.9.1
]]>
</screen>
<para>除了 TCP 方式连接,还支持 IPC 方式。这种方式比较少用,可以使用 localhost 替代。</para>
<programlisting>
<![CDATA[
// OS X/Linux/Unix:
Web3j web3 = Web3j.build(new UnixIpcService("/path/to/socketfile"));
...
// Windows
Web3j web3 = Web3j.build(new WindowsIpcService("/path/to/namedpipefile"));
...
]]>
</programlisting>
</section>
<section id="web3j.account">
<title>账号管理</title>
<section>
<title>获得账号列表</title>
<programlisting>
<![CDATA[
public List<String> getAccountlist() {
try {
return web3j.ethAccounts().send().getAccounts();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
]]>
</programlisting>
</section>
<section>
<title>获得账号信息</title>
<programlisting>
<![CDATA[
public String getAccount(int index) {
String account = null;
try {
account = web3j.ethAccounts().send().getAccounts().get(index);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return account;
}
]]>
</programlisting>
</section>
<section id="web3j.personalUnlockAccount">
<title>解锁账号</title>
<programlisting>
<![CDATA[
Admin web3j = Admin.build(new HttpService()); // defaults to http://localhost:8545/
PersonalUnlockAccount personalUnlockAccount = web3j.personalUnlockAccount("0x000...", "a password").sendAsync().get();
if (personalUnlockAccount.accountUnlocked()) {
// send a transaction
}
]]>
</programlisting>
</section>
<section id="web3j.account.example">
<title>例子</title>
</section>
</section>
<section id="web3j.credentials">
<title>Credentials</title>
<programlisting>
<![CDATA[
package cn.netkiller.ethereum.credentials;
import java.io.IOException;
import java.math.BigInteger;
import org.web3j.crypto.Credentials;
import org.web3j.crypto.ECKeyPair;
import org.web3j.protocol.Web3j;
import org.web3j.protocol.http.HttpService;
public class CredentialsTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
String url = "http://172.16.0.1:8545/";
Web3j web3j = Web3j.build(new HttpService(url)); // defaults to http://localhost:8545/
try {
String account = web3j.ethAccounts().send().getAccounts().get(0);
Credentials credentials = Credentials.create(account);
ECKeyPair keyPair = credentials.getEcKeyPair();
BigInteger privateKey = keyPair.getPrivateKey();
BigInteger publicKey = keyPair.getPublicKey();
System.out.println(privateKey);
System.out.println("---");
System.out.println(publicKey);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}