-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbitcoin.tx.sh
executable file
·1588 lines (1347 loc) · 40.7 KB
/
bitcoin.tx.sh
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
#!/usr/bin/env bash
# v0.9.12 feb/2023 by mountaineerbr
# parse transactions by hash or transaction json data
# requires bitcoin-cli and jq 1.6+
#set simple verbose
#feedback to stderr
OPTVERBOSE=0
#cache dir for results copy
#eg. ~/.cache/bitcoin.tx
CACHEDIR="$HOME/.cache/bitcoin.tx"
#check user cache disk usage
#(prints warning when exceeded)
MAXCACHESIZE=150000000 #150MB
#maximum jobs (subprocesses)
JOBSDEF=4
#this depends mainly on the number of threads to service rpc calls of
#bitcoin daemon config sets (rpcthreads=<n> ,defaults: 4)
#as the number of independent api requests that can be processed in parallel.
#in reality however there are many locks inside the product that means you
#won't see much performance benefit with a value above your processor number.
#semaphore sleep time (i5)
#!#this is highly dependent on your machine processor!
#!#may tune to improve speed a little
SEMAPHORESLEEP=0.11
#set calculation scale (mainf fun)
SCL=8
#white paper
#out file
WPOUTFILE=bitcoinWP.pdf
#whitepaper transaction hash and block hash
WPTXID=54e48e5f5c656b26c3bca14a8c95aa583d07ebe84dde3b7dd4a78f4e4186e713
WPBLKHX=00000000000000ecbbff6bafb7efa2f7df05b227d5c73dca8f2635af32a2e949
#timezone
#defaults=UTC0
TZ="${TZ:-UTC0}"
export TZ
#temporary directory path
#$TMPDIR has higher precedence
#try to keep temp files in shared memory (ramdisc)
TMPDIR1=/dev/shm
#make sure locale is set correctly
#LC_NUMERIC=C
LANG=C LC_ALL=C
#printf clear line
CLR='\033[2K'
#script name
SN="${0##*/}"
#genesis block hash (same as coinbase tx hash)
#requesting this may throw errors in some funcs
#GENBLK_HASH=000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f
#get tx with `bitcoin-cli getblock $GENBLK_HASH 2`
#help
HELP="NAME
$SN - Parse transactions by hash or transaction json data
SYNOPSIS
$SN [-afklouvyy] [-j[NUM]] [-bBLOCK_HASH|HEIGHT] TRANSACTION_HASH..
$SN [-afklouvyy] [-j[NUM]] \"TRANSACTION_HASH [BLOCK_HASH|HEIGHT]\"..
$SN [-s|-S[VOUT]] [-j[NUM]] \"TRANSACTION_HASH [BLOCK_HASH|HEIGHT]\"..
$SN -hVww
DESCRIPTION
Given a TRANSACTION_HASH, the script will make an RPC call to
bitcoin-cli and parse the returning JSON data. Parsed transact-
ions are concatenated as per input order to a single file at
${CACHEDIR/$HOME/\~} and printed to stdout.
Transaction ids/hashes may be sent through stdin or set as posi-
tional parameters to the script.
An argument or line from stdin may have two words separated by
a blank space: the first one is the TRANSACTION_HASH and the
second word must be BLOCK_HASH or HEIGHT of that transaction.
Setting a BLOCK_HASH or HEIGHT is required if bitcoin-daemon is
not set with txindex=1 option.
Option -f prints only general transaction information and does
not retrieve vins and vouts but is very fast. Pass multiple times
to dump more data. If used with multiple jobs, transaction output
order may differ from input; note that this option does not save
a copy of output.
General Options
Option -c CONFIGFILE sets the configuration file path (bitcoin.conf)
if that is in a custom location other than defaults, see also
section ENVIRONMENT.
Option -l sets local time instead of UTC time.
Option -u prints time in human-readable format RFC 5322 instead
of the defaults ISO 8601.
Option -v enables verbose, set -vv to print more feedback for
some functions.
Job Control
Set option -o to print to stdout while processing; beware trans-
actions may not be printed in the input order; this option dis-
ables writing results to cache at ${CACHEDIR/$HOME/\~} .
Set option -jNUM in which NUM is an integer and sets the maximum
number of simultaneous background jobs, in which case NUM must be
an integer or \`auto'. Environment variable \$JOBSMAX is read,
defaults=${JOBSDEF} . Only with the defaults and -f functions.
Beware that when -o is set with the defaults function or -f is set,
asynchronous jobs may lose the print lock momentarily for another
job and output may get mixed. To avoid that, try setting -j1 .
Other Functions
Option -y will convert plain hex dump from a transaction to ASCII
text. The output will be filtered to print sequences that are at
least 20 characters long, unless that returns empty, in which case
there is decrement of one character until a match is found. If
nought is reached, the raw byte output will be printed. Setting
-yy prints all raw byte sequences, see example (4).
Option -s checks if TXID VOUTS are all unspent, otherwise exits
with one error per TXID. To check only certain VOUT numbers, set
-S[VOUT] as many times as required, in which VOUT is a positive
integer, check example (7). Printed fields: Txid, Vout_n, Check,
[Value], [Coinbase] and [Addresses].
Extra Functions
Option -w will regenerate bitcoin white paper. Two methods are
available, either from the transaction itself (fast, -w) or from
the UTXO set (slow, -ww). An output PDF file will be created at
\$PWD, defaults=$WPOUTFILE. See section SEE ALSO for more
information.
If -b is set with a BLOCK_HASH or BLOCK_HEIGHT, no positional
argument is set and stdin is free, parse all transactions from
that block, see also option -f; e.g. \`$SN -ff -b100000\`.
ENVIRONMENT VARIABLES
BITCOINCONF
Path to bitcoin.conf or equivalent file with configs
such as RPC user and password, is overwritten by script
option -c, defaults=\"\$HOME/.bitcoin/bitcoin.conf\".
TMPDIR Sets user custom temporary directory, if unset defaults
to $TMPDIR1 or /tmp .
TZ Sets timezone, defaults to UTC0 (GMT).
SEE ALSO
bitcoin.blk.sh -- Bitcoin block information and functions;
from the same suite of this present script
<https://github.com/mountaineerbr/scripts>
bitcoin.sh -- Grondilu's Bitcoin bash functions
<https://github.com/grondilu/bitcoin-bash-tools>
blockchain-parser -- Ragestack's blockchain binary data parser
<https://github.com/ragestack/blockchain-parser>
Bitcoin whitepaper in the blockchain
<https://bitcoinhackers.org/@jb55/105595146491662406>
<https://bitcoin.stackexchange.com/questions/35959/how-is-the-whitepaper-decoded-from-the-blockchain-tx-with-1000x-m-of-n-multisi/35970#35970>
Q. What's the difference between \`txid' and \`hash'?
A. when tx is segwit, calculation of \`hash' does not include
witness data, whereas the \`txid' does.
<https://bitcoin.stackexchange.com/questions/77699/whats-the-difference-between-txid-and-hash-getrawtransaction-bitcoind>
WARRANTY
Licensed under the gnu general public license 3 or better and
is distributed without support or bug corrections.
Grondilu's bitcoin-bash-tools functions are embedded in this
script, see <https://github.com/grondilu/bitcoin-bash-tools>.
Packages bitcoin-cli v0.21+, jq 1.6+, openssl, xxd, sha256sum
and bash v4+ are required.
If you found this programme interesting or useful, please
consider sending feedback! =)
USAGE EXAMPLES
1) Get transaction information; commands below should be equiv-
alent; setting block hash is only necessary if bitcoin daemon is
not set with txindex :
$ $SN -b0000000000000000000fb6a4d6f5dc7438f91a1bc3988c4f32b4bb8284eed0ec \\
a8bb9571a0667d63eaaaa36f9de87675f0d430e13c916248ded1d13093a77561
$ $SN -b 638200 a8bb9571a0667d63eaaaa36f9de87675f0d430e13c916248ded1d13093a77561
$ $SN 'a8bb9571a0667d63eaaaa36f9de87675f0d430e13c916248ded1d13093a77561 0000000000000000000fb6a4d6f5dc7438f91a1bc3988c4f32b4bb8284eed0ec'
$ echo 'a8bb9571a0667d63eaaaa36f9de87675f0d430e13c916248ded1d13093a77561 638200' | $SN
2) Process transaction JSON from bitcoin daemon:
$ TRANSACTION_HASH=a8bb9571a0667d63eaaaa36f9de87675f0d430e13c916248ded1d13093a77561
$ BLOCK_HEIGHT=638200
$ BLOCK_HASH=\$( bitcoin-cli getblockhash \$BLOCK_HEIGHT )
$ bitcoin-cli getrawtransaction \"\$TRANSACTION_HASH\" true \"\$BLOCK_HASH\" | $SN
3) Examples (1) and (2) are equivalent to:
$ $SN -b\"\$BLOCK_HASH\" \"\$TRANSACTION_HASH\"
4) Decode hex code to ASCII text using \`strings\`:
$ $SN -y 930a2114cdaa86e1fac46d15c74e81c09eee1d4150ff9d48e76cb0697d8e1d72
$ $SN -yy 930a2114cdaa86e1fac46d15c74e81c09eee1d4150ff9d48e76cb0697d8e1d72 | strings -n 20
$ strings -n 20 blk00003.dat #decode the whole block file
5) Get the genesis block coinbase transaction and parse it:
$ bitcoin-cli getblock \$(bitcoin-cli getblockhash 0) 2 | $SN
$ bitcoin.blk.sh -ii 0 | $SN
6) Parse all transactions from best block; note that bitcoin.blk.sh
is a companion suite script from the same author:
$ bitcoin.blk.sh -g | $SN -ff #fast, less tx info
$ bitcoin.blk.sh -ii | $SN #slow, detailed tx info
7) Check for unspent transaction outputs from a block:
$ bitcoin.blk.sh -ii | head | $SN -s #check all tx vouts
$ bitcoin.blk.sh -ii | head | $SN -S\"0 1\" #check only vouts 1 and 2
OPTIONS
Extra Functions
-w Regenerate bitcoin whitepaper, may set twice; outfile=$WPOUTFILE.
Miscellaneous
-h Print this help page.
-V Print script version.
-v Verbose, may set multiple times.
General
-a Do not try to compress addresses (print assembly).
-b BLOCK_HASH
Set block hash containing transactions.
-c CONFIGFILE
Path to bitcoin.conf or equivalent configuration file,
defaults=\"\$HOME/.bitcoin/bitcoin.conf\".
Job control
-j NUM Maximum number of simultaneous jobs, defaults=${JOBSDEF} .
Output and format control
-l Sets local time instead of UTC time.
-o Send to stdout while processing, inhibits creation of
results file at ${CACHEDIR/$HOME/\~} .
-u Print time in RFC5322 instead of ISO8601.
Functions
-f General transaction information only (fast), set multiple
times to dump more data.
-s Check if TXID VOUTS are all unspent.
-S VOUT Same as -s but checks specific VOUTs, may set multiple times.
-y Decode transaction hex to ASCII (auto select string length).
-yy, -Y Same as -y but prints all bytes."
#!#bitcoin.sh snapshot with custom modifications
#!#commit: 95860e1567e2def6f95fb77212ea53015016ab6a
#!#date: 24/jan/2021
#
# Various bash bitcoin tools
#
# requires dc, the unix desktop calculator (which should be included in the
# 'bc' package)
#
# This script requires bash version 4 or above.
#
# This script uses GNU tools. It is therefore not guaranted to work on a POSIX
# system.
#
# Copyright (C) 2013 Lucien Grondin ([email protected])
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
pack() {
echo -n "$1" |
xxd -r -p
}
unpack() {
xxd -p | tr -d '\n'
}
declare -a base58=(
1 2 3 4 5 6 7 8 9
A B C D E F G H J K L M N P Q R S T U V W X Y Z
a b c d e f g h i j k m n o p q r s t u v w x y z
)
unset dcr; for i in {0..57}; do dcr+="${i}s${base58[i]}"; done
decodeBase58() {
echo -n "$1" | sed -e's/^\(1*\).*/\1/' -e's/1/00/g' | tr -d '\n'
echo "$1" |
{
echo "$dcr 0"
sed 's/./ 58*l&+/g'
echo "[256 ~r d0<x]dsxx +f"
} | dc |
while read n
do printf "%02X" "$n"
done
}
encodeBase58() {
local n
echo -n "$1" | sed -e's/^\(\(00\)*\).*/\1/' -e's/00/1/g' | tr -d '\n'
dc -e "16i ${1^^} [3A ~r d0<x]dsxx +f" |
while read -r n; do echo -n "${base58[n]}"; done
}
checksum() {
pack "$1" |
openssl dgst -sha256 -binary |
openssl dgst -sha256 -binary |
unpack |
head -c 8
}
hash160() {
openssl dgst -sha256 -binary |
openssl dgst -rmd160 -binary |
unpack
}
hexToAddress() {
local x="$(printf "%2s%${3:-40}s" ${2:-00} $1 | sed 's/ /0/g')"
encodeBase58 "$x$(checksum "$x")"
echo
}
#original script funcs
#get a bitcoin whitepaper pdf copy
whitepaperf()
{
#From the UTXO set (slow)
#bare multisig outputs that will never be spent
if ((OPTW>1))
then
for ((n=0;n<948;++n))
do
((OPTVERBOSE)) && printf 'utxo: %3d/%3d \r' $((n+1)) 948 >&2
bwrapper gettxout $WPTXID $n |
jq -r '.scriptPubKey.asm' |
awk '{ print $2 $3 $4 }'
done \
| tr -d '\n' \
| cut -c 17-368600 \
| xxd -r -p >"$WPOUTFILE"
#From blockchain transaction (defaults, fast)
else
bwrapper getrawtransaction $WPTXID 0 $WPBLKHX \
| sed 's/0100000000000000/\n/g' \
| tail -n +2 \
| cut -c7-136,139-268,271-400 \
| tr -d '\n' \
| cut -c17-368600 \
| xxd -p -r >"$WPOUTFILE"
fi
((OPTVERBOSE)) && echo >&2
echo "$SN: file generated -- $WPOUTFILE" >&2
}
#https://bitcoin.stackexchange.com/questions/35959/how-is-the-whitepaper-decoded-from-the-blockchain-tx-with-1000x-m-of-n-multisi/35970#35970
#https://bitcoinhackers.org/@jb55/105595146491662406
#err signal
errsigf()
{
local sig="${1:-1}"
echo "$sig" >>"$TMPERR"
}
#is transaction hash?
#ishashf() { [[ "$1" =~ ^[a-fA-F0-9]{64}$ ]] ;}
#tx hex to ascii
hexasciif()
{
local ascii hex num #BLOCK_HASH_LOOP
if
#read file $TMP3 or get json from bitcoin-cli
if [[ -e "$TMP3" ]]
then hex="$(jq -r '.hex // empty' "$TMP3")"
else hex="$(bwrapper getrawtransaction "$TXID" true ${BLOCK_HASH_LOOP:-${BLK_HASH}} | jq -r '.hex // empty')"
fi
[[ -n "$hex" ]]
then
#verbose?
#clear last feedback line in stderr
((OPTVERBOSE)) && printf "$CLR" >&2
if ((OPTVERBOSE > 1))
then
#<<<"$txdata" jq -r '.vin[0] | if .coinbase then "(coinbase transaction)\\n" else empty end'
echo -ne "--------\nTXID: ${TXID:-${COUNTER:-(json)}}\nHEX_: $hex\nASCI: "
fi
#print ascii text
if ((OPTASCII>1))
then
<<<"$hex" xxd -r -p
else
#if strings result is not empty
#decode hex to ascii (ignore null byte warning)
{ ascii="$(<<<"$hex" xxd -r -p)" ;} 2>/dev/null
for ((num=20 ;num>=0 ;--num))
do
((num)) || break
strs="$( strings -n "$num" <<<"$ascii" )"
#-n Print sequences of characters that are
#at least min-len characters long, instead of the default 4
[[ -n "${strs// /}" ]] && break
done
#decide how to print
#there was some output from `strings`
if ((num))
then echo "$strs"
#otherwise print the raw ascii
else <<<"$hex" xxd -r -p
fi
fi
#print simple feedback
((OPTVERBOSE)) &&
printf "tx: %*d/%*d \r" "$K" "$((COUNTER+1))" "$K" "$L" >&2
else
return 1
fi
return 0
}
#nelson mandela transaction
#hash:8881a937a437ff6ce83be3a89d77ea88ee12315f37f7ef0dd3742c30eef92dba
#hex:334E656C736F6E2D4D616E64656C612E6A70673F
#Len Sassaman Tribute
#txid:930a2114cdaa86e1fac46d15c74e81c09eee1d4150ff9d48e76cb0697d8e1d72
#Satoshi Nakamoto email
#txid:77822fd6663c665104119cb7635352756dfc50da76a92d417ec1a12c518fad69
#very good (there is a how to)
#http://www.righto.com/2014/02/ascii-bernanke-wikileaks-photographs.html
#alternative main, faster method, process less info
mainfastf()
{
#print simple feedback
(( OPTVERBOSE )) &&
printf "${CLR}tx: %*d/%*d \r" "$K" "$((COUNTER+1))" "$K" "$L" >&2
#vins and vouts and general info
if ((OPTFAST>1))
then
#dumps more data
jq -r --arg optf "$OPTFAST" '"",
"--------",
"Input and output vectors",
"",
"Vins",
(
.vin[] // empty |
(
" TxIndex_: \(.txid // "coinbase")",
" Sequence: \(.sequence)\tVoutNum: \(.vout // "??")",
(
.scriptSig |
" ScSigTyp: \(.type // empty)",
" ScSigAsm: \( if ($optf | tonumber) > 2 then (.asm // empty) else empty end)",
""
),
""
)
),
"Vouts",
(
.vout[] |
" Number__: \(.n )\tValue__: \(.value )",
(
.scriptPubKey |
" PKeyType: \(.type // empty)\(if .reqSigs then "\tReqSigs: \(.reqSigs)" else "" end)",
" PKeyAddr: \( .address? // (.addresses | .[]?) // empty )",
" PKeyAsm_: \( if ($optf | tonumber) > 2 then (.asm // empty) else empty end )",
""
)
),
'"$JQTXINFO" "$@"
#reqSigs was deprecated and .addresses array changed to vector in release bitcoin-daemon 22.0
#.txinwitness not added because it dumps too much info
else
#dumps only basic info
jq -r '"",
"--------",
'"$JQTXINFO" "$@"
fi
}
#parse engine
parsef()
{
#set to concatenate results
CONCAT=1
#processed transaction temp file
TMP4="${TMPD}/${COUNTER}.tx"
#raw transaction (json) temp file
TMP3="$TMP4.json"
#!#must be the same as in other functions
#manage jobs
jobsemaphoref
#make sure file exists for later concatenation
#(even if empty)
: >"$TMP4"
#make an array with processed transaction files
TXFILES+=( "$TMP4" )
#processing pipeline (to bg)
{
#is tx json already? Else, get tx json
if ((JSON)) || {
#consolidate $BLK_HASH (if set)
BLK_HASH="${BLK_HASH_LOOP:-${BLK_HASH}}"
#do some basic checking
#is $BLK_HASH set?
if [[ -n "${BLK_HASH// }" ]]
then
#is "block hash" set as "block height"?
if [[ "$BLK_HASH" =~ ^[0-9]{,7}$ ]]
then
BLK_HASH="$( bwrapper getblockhash "$BLK_HASH" )" || { errsigf $?; exit 1;}
#is it really NOT "block hash"?
elif [[ ! "$BLK_HASH" =~ ^[0]{8}[a-fA-F0-9]{56}$ ]]
then
#print error msg
echo ">>>error: block hash -- $BLK_HASH" >&2
errsigf 1
exit 1
fi
fi
#check that $TXID is a transaction hash
if [[ ! "$TXID" =~ ^[a-fA-F0-9]{64}$ ]] #is $TXID a tx hash?
then
#print error msg
echo ">>>error: transaction id -- $TXID" >&2
errsigf 1
exit 1
fi
#get raw transaction json
bwrapper getrawtransaction "$TXID" true $BLK_HASH >"$TMP3"
}
then
# MAIN
typeset -a vinsum voutsum catvin catvout
#one transaction json at a time!
{
#vins
echo -e "\n--------\nInput and output vectors\nVins"
#temp file for sum of vins
index=0 tmp10sum="$TMP3.vin.sum"
#loop through indexes
while
header="$( jq -re --arg index "$index" '.vin[($index|tonumber)] // empty |
" TxIndex: \(.txid // empty)",
" Sequenc: \(.sequence)\( if .vout then "\tVoutNum: \(.vout)" else "" end)"' "$TMP3" 2>/dev/null )"
#" Witness: \(.txinwitness //empty | @sh)"
#.txinwitness not added because it dumps too much info
do
#temp file for vin
tmp10="$TMP3.$index.vin" catvin+=( "$tmp10" )
#manage jobs
jobsemaphoref
#async loop
{
#get addrs
#also sets $tmp10sum
echo "$header"
if ! vinf "$TMP3"
then echo ' skipping addresses..' ;errsigf 1
fi 2>/dev/null
echo
#print simple feedback
(( OPTVERBOSE )) &&
printf "${CLR}tx: %*d/%*d in : %3d \r" "$K" "$((COUNTER+1))" "$K" "$L" "$((index+1))" >&2
} >"$tmp10" &
(( ++index ))
done
wait
printf '%s\0' "${catvin[@]}" | xargs -0 -r cat
#vouts
echo -e "\nVouts"
#temp file for sum of vouts
index=0 tmp11sum="$TMP3.vout.sum"
#loop through indexes
while
header="$( jq -re --arg index "$index" '.vout[($index|tonumber)] // empty |
" Number_: \(.n )\tValue__: \(.value )"' "$TMP3" 2>/dev/null )"
do
#temp file for vout
tmp11="$TMP3.$index.vout" catvout+=( "$tmp11" )
#manage jobs
jobsemaphoref
#async loop
{
echo "$header"
#get addrs
if ! voutf "$TMP3"
then echo ' skipping addresses..' ;errsigf 1
fi 2>/dev/null
echo
#save for sum later
jq -r --arg index "$index" '.vout[($index|tonumber)] // "0" | .value' "$TMP3" >>"$tmp11sum" 2>/dev/null
#print simple feedback
(( OPTVERBOSE )) &&
printf "${CLR}tx: %*d/%*d out: %3d \r" "$K" "$((COUNTER+1))" "$K" "$L" "$((index+1))" >&2
} >"$tmp11" &
(( ++index ))
done
wait
printf '%s\0' "${catvout[@]}" | xargs -0 -r cat
#general info
jq -r "\"\",$JQTXINFO" "$TMP3"
#sum vouts
#load values from file
#change "e" to "*10^", may use GLOBIGNORE=\* and sed
voutsum=( $(<"$tmp11sum") ) voutsum=( "${voutsum[@]//e/*10^}" )
#calc sums
out="$( bc <<<"scale=$SCL ;( ${voutsum[@]/%/+} 0 ) /1" )"
#sum vins
#load values from file
vinsum=( $(<"$tmp10sum") )
if [[ "${vinsum[*]}" = *coinbase* ]]
then
in=coinbase fee=0
else
#change e to *10^
vinsum=( "${vinsum[@]//e/*10^}" )
#calc sums
in="$( bc <<<"scale=$SCL ;( ${vinsum[@]/%/+} 0 ) /1" )" fee="$( bc <<<"scale=$SCL ;( $in-$out ) /1" )"
fi
#format results
#count longest number characters
for c in "$in" "$out" "$fee"
do ((${#c}>cc)) && cc="${#c}"
done
#is coinbase?
[[ "$in" != *coinbase* ]] && in="$(printf '%+*.*f\n' "$cc" "$SCL" "$in")"
out="$( printf '%+*.*f\n' "$cc" "$SCL" "$out" )" fee="$( printf '%+*.*f\n' "$cc" "$SCL" "$fee" )"
#calc transaction fee per vByte and total fee
feerates=(
$(jq -r "((${fee//[.+-]/} / .size )|if . < 1000 and . > 0.01 then tostring|.[0:5] else . end),
((${fee//[.+-]/} / .vsize )|if . < 1000 and . > 0.01 then tostring|.[0:5] else . end),
((${fee//[.+-]/} / .weight)|if . < 1000 and . > 0.01 then tostring|.[0:5] else . end)" "$TMP3")
)
##feerates=( "${feerates[@]%.*}" )
#tere are many units for calculating transaction fee
#per byte, per virtual bye and per weight unit
#one virtual byte = 4 weight units
#the defaults should be `sats/vB'
#https://bitcointalk.org/index.php?topic=5250569.0
#https://bitcointalk.org/index.php?topic=5251213.0
#https://btc.network/estimate
echo "Vin__Sum: ${in:-?}
Vout_Sum: ${out:-?}
Tx___Fee: ${fee:-?}
FeeRates: ${feerates[0]:-?} sat/B ${feerates[1]:-?} sat/vB ${feerates[2]:-?} sat/WU"
} >"$TMP4"
#remove buffer files
rm -- "$tmp10sum" "$tmp11sum" "${catvout[@]}" "${catvin[@]}"
unset catvin catvout header index tmp10 tmp10sum tmp11 tmp11sum vinsum voutsum in out fee feerates c cc
#write to stdout while processing?
if (( OPTOUT ))
then
#clear last feedback line
(( OPTVERBOSE )) && printf "$CLR" >&2
cat -- "$TMP4"
fi
else
#print error
echo ">>>error: transaction id -- $TXID" >&2
errsigf
fi
#clean up on the fly
rm -- "$TMP3" 2>/dev/null
} &
}
#note: use bitcoin.tx.sh with option '-bBLOCK_HASH'
#if bitcoind option txindex is not set
#jq slurp tip:https://stackoverflow.com/questions/41216894/jq-create-empty-array-and-add-objects-to-it
parsefastf()
{
#manage jobs
jobsemaphoref
#processing pipeline (to bg)
{
#consolidate $BLK_HASH (if set)
BLK_HASH="${BLK_HASH_LOOP:-${BLK_HASH}}"
#do some basic checking
#is $BLK_HASH set?
if [[ -n "${BLK_HASH// }" ]]
then
#is "block hash" set as "block height"?
if [[ "$BLK_HASH" =~ ^[0-9]{,7}$ ]]
then
BLK_HASH="$( bwrapper getblockhash "$BLK_HASH" )" || { errsigf $?; exit 1;}
#is it really NOT "block hash"?
elif [[ ! "$BLK_HASH" =~ ^[0]{8}[a-fA-F0-9]{56}$ ]]
then
#print error msg
echo ">>>error: block hash -- $BLK_HASH" >&2
errsigf 1
exit 1
fi
fi
#check that $TXID is a transaction hash
if [[ ! "$TXID" =~ ^[a-fA-F0-9]{64}$ ]] #is $TXID a tx hash?
then
#print error msg
echo ">>>error: transaction id -- $TXID" >&2
errsigf 1
exit 1
fi
#get raw transaction json
bwrapper getrawtransaction "$TXID" true $BLK_HASH | mainfastf
} &
}
#break asm and remove some script strings - helper func
#it would be useful to have a script code library with byte translations
#so we could process asm (assembly) better or even the hex code directly
#https://en.bitcoin.it/wiki/Script#Constants
asmbf()
{
local string
for string
do
#remove strings with chars '_][' or jq null output
if [[ "$string" = *[\[\]_]* || "$string" = null ]]
then continue
else echo "$string"
fi
done
}
#do not activate this now, may need eventually,
#break asm (string[EXAMPLE]) -> (string [EXAMPLE])
#A=( ${ASM[@]//\[/ [} ) ;A=( ${A[@]//\]/] } )
#check addresses -- helper func
#used in vinbakf only
seladdrf()
{
local TADDR
TADDR=( ${ADDR[@]//null} )
((${#TADDR[@]}))
}
#select correct asm ( experimental! ) -- helper func
#used in vinbakf only
selasmf()
{
ASM=( $( asmbf "$@" ) )
((${#ASM[@]}))
}
#vouts
#defaults voutf function
#this function has many fallbacks if bitcoind is not set with txindex
#and it will try and decode an address from asm/hex
#old code, tested a lot, avoid changing it, cannot retest all fallbacks again
voutf()
{
local ADDR ASM TYPE TMP pubKeyAddr pubKeyAsm pubKeyType isunspent
TMP="$1"
#set variables for address processing
#that is risky to set them all at once, but faster
#the following shell arrays or variables will be set:
#$pubKeyAddr, $pubKeyAsm and $pubKeyType
eval "$(
jq -r --arg index "$index" '.vout[($index | tonumber)].scriptPubKey |
(
"pubKeyAddr=( \( .address? // (.addresses | .[]?) // empty ) )",
"pubKeyAsm=( \( .asm? // empty ) )",
"pubKeyType=\"\( .type? // empty )\""
)' "$TMP"
)"
#is spent?
[[ "$pubKeyType" = nulldata ]] || isunspent="$(unspentcheckvoutf)"
#try to hash uncompressed addresses
if (( ${#pubKeyAddr[@]} ))
then
#1#
TYPE="$pubKeyType"
echo " Type___: ${TYPE}""${isunspent}"
printf ' %s\n' "${pubKeyAddr[@]}"
elif ASM=( $( asmbf "${pubKeyAsm[@]}" ) )
(( ${#ASM[@]} ))
then
TYPE="$pubKeyType"
echo " Type___: ${TYPE}""${isunspent}"
#if nulldata
#or if option -a (don't try to compress address) is set, print raw
if [[ "$TYPE" = nulldata || "$OPTADDR" -gt 0 ]]
then
#2#
echo " ${ASM[-1]}"
#if string is hashed
#3.0
elif [[ "$TYPE" = *pubkeyhash* ]]
then
echo "$( hexToAddress "${ASM[-1]}" 00 )"
#3.1
elif [[ "$TYPE" = *scripthash* ]]
then
echo "$( hexToAddress "${ASM[-1]}" 05 )"
else
#4#
echo " $( hexToAddress "$( pack "${ASM[-1]}" | hash160 )" 00 )"
fi
else
#10#
#exit with error signal
return 1
fi
return 0
}
#analysis# the following conditionals are used frequently
#by tx processing from various blocks: #1#, #2# and #4#
#when no .address field is found, falls back to #3.x#
#however, there are many fallbacks..
#debug: voutf count usage: echo "#$n# ${TXID}" >&2
#vins
#defaults vinf function
#this function has some fallbacks
#for when bitcoind is not set with txind=1
vinf()
{
local TMP TMP2 txid ret
typeset -a txid ret
TMP="$1"
#go back to previous transaction to get some data..
txid=( $(
jq -er --arg index "$index" \
'.vin[($index | tonumber)] |
.txid,
.vout,
(if .coinbase then "coinbase" else empty end)' \
"$TMP"
) ) || return 1
#temp file
TMP2="$TMP.${txid[0]:0:20}.$index"
#is coinbase?
if [[ "${txid[-1]}" = coinbase ]]
then
vinsum+=(coinbase)
echo " coinbase"
#get previous transaction
elif bwrapper getrawtransaction "${txid[0]}" true >"$TMP2"
then
jq -r --arg index "${txid[-1]}" '.vout[($index | tonumber)] // empty | " Number_: \(.n )\tValue__: \(.value )"' "$TMP2"
index="${txid[-1]}" voutf "$TMP2"
else
#backup func
#if bitcoind txindex is not set,
#this func may still parse some addresses..
vinbakf "$TMP" && return
fi
#get exit code
((ret += $?))
#save result for sum later if no error exit code
if ((! ret))
then if [[ "${vinsum[0]}" = coinbase ]]
then echo coinbase
else jq -r --arg index "${txid[-1]}" '.vout[( $index | tonumber)] // "0" | .value' "$TMP2"
#clean up on the fly
rm -- "$TMP2" 2>/dev/null
fi
else :
fi >>"$tmp10sum"
return $ret
}
#backup vinf function
#if bitcoind txindex is not set,
#this func may still process some addresses..
vinbakf()
{
local TMP="$1"
if ADDR=( $( jq -er --arg index "$index" '.vin[($index | tonumber)].scriptPubKey | (.address? // (.addresses | .[]?))' "$TMP" ) ) &&
seladdrf
then
#1#