1+ <?php
2+
3+ include '../vendor/autoload.php ' ;
4+
5+ $ blockDir = getenv ('HOME ' ) . '/Library/Application Support/Bitcoin/blocks ' ;
6+
7+ $ reader = new \AndKom \PhpBitcoinBlockchain \BlockFileReader ();
8+
9+ // txid:index => balance
10+ $ outputs = [];
11+
12+ // txid:index => address
13+ $ addresses = [];
14+
15+ foreach ($ reader ->read ($ blockDir . '/blk00000.dat ' ) as $ block ) {
16+
17+ foreach ($ block ->transactions as $ tx ) {
18+ foreach ($ tx ->inputs as $ in ) {
19+ if ($ in ->isCoinbase ()) continue ;
20+
21+ $ prev = $ in ->prevTxHash . ': ' . $ in ->prevTxOutIndex ;
22+ $ outputs [$ prev ] = 0 ;
23+ }
24+
25+ $ txid = $ tx ->getHash ();
26+
27+ foreach ($ tx ->outputs as $ index => $ out ) {
28+ try {
29+ $ address = $ out ->scriptPubKey ->getOutputAddress ();
30+ } catch (\Exception $ e ) {
31+ $ address = 'unknown script: ' . $ out ->scriptPubKey ;
32+ }
33+
34+ $ output = "$ txid: $ index " ;
35+
36+ if (!isset ($ outputs [$ output ])) {
37+ $ outputs [$ output ] = 0 ;
38+ }
39+
40+ $ outputs [$ output ] += $ out ->value ;
41+ $ addresses [$ output ] = $ address ;
42+ }
43+ }
44+ }
45+
46+ $ balances = [];
47+
48+ foreach ($ outputs as $ out => $ value ) {
49+ // @todo address may not exists because blocks are unordered
50+ $ address = $ addresses [$ out ];
51+
52+ if (!isset ($ balances [$ address ])) {
53+ $ balances [$ address ] = 0 ;
54+ }
55+
56+ $ balances [$ address ] += $ value ;
57+ }
58+
59+ arsort ($ balances );
60+
61+ foreach ($ balances as $ address => $ balance ) {
62+ echo $ address . ' => ' . bcdiv ($ balance , 1e8 , 8 ) . " BTC \n" ;
63+ }
0 commit comments