Repository navigation
Expand file tree
/
Copy pathtcls_create.sh
More file actions
1583 lines (1483 loc) · 58.2 KB
/
Copy pathtcls_create.sh
File metadata and controls
1583 lines (1483 loc) · 58.2 KB
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
#!/bin/sh
# tool to create a raw, unsigned bitcoin transaction or msig addresses and redeem script
#
# Copyright (c) 2015, 2016 Volker Nowarra
# Coded in June 2016 following this reference:
# https://en.bitcoin.it/wiki/Protocol_specification#tx
# http://bitcoin.stackexchange.com/questions/3374/how-to-redeem-a-basic-tx
#
# Version by date comment
# 0.1 svn 13jul16 initial release from previous "trx2txt" (discontinued) code
# 0.2 svn 20dec16 rework of fee calculation
# 0.3 svn 05feb17 multisig function included
# 0.4 svn 19may17 improved fee handling and presentation at the end
# 0.5 svn 06jul17 if creating a tx to an address beginning with "3", the script
# should detect this (p2sh), and use OP_HASH160 OP_DATA_20 OP_EQUAL ...
# 0.6 svn 02dec17 I19: trx validation and limits
# 0.7 svn 17mar18 I63: removed external fee source, improved output
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
# SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER
# RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
# NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE
# USE OR PERFORMANCE OF THIS SOFTWARE.
#
#
###########################
# Some variables ... #
###########################
typeset -i i=0
# flags used when calling the script with different parameters
typeset -i c_param_flag=0 # create a new TX
typeset -i f_param_flag=0 # create TX with inputs from file
typeset -i m_param_flag=0 # multisig adress and redeemscripthash
typeset -i t_param_flag=0 # fetch TX Input data from blockchain
typeset -i T_param_flag=0 # Testnet
typeset -i std_sig_chars=90 # expected chars that need to be added, to calculate txfee
# values from previous transaction
utxo_TX_ID=''
utxo_OutPoint=''
utxo_PKScript=''
utxo_Amount=''
# variables for output and txfee calculation
# compressed pubkey, tx size = a*148 + b*34 + 10 +/- 1
# uncompressed pubkey, tx size = a*180 + b*34 + 10 +/- 1
typeset -i amount=0
typeset -i txfee_param_flag=0 # to calculate tx fee
typeset -i txfee_per_byte=0 # txfee from the parameter to the script
typeset -i a_txfee_per_byte=0 # adjusted tx fee in Satoshi per byte
typeset -i a_txfee=0 # calculated adjusted tx fee
typeset -i c_txfee=0 # calculated tx fee
typeset -i f_txfee=0 # file tx fee
# typeset -i BF21_txfee_per_byte=0 # bitcoinfees.21.co/api/v1/fees/recommended
# typeset -i BF21_txfee=0 # calculated txfees based on bitcoinfees.21.co
typeset -i TX_amount=0 # the requested TX amount
typeset -i prev_tx_utxo_amount=0 # to calculate tx fee
typeset -i file_utxo_amount=0 # utxo amounts from a file
typeset -i d_amount=0 # delta amount (input - output - txfees)
typeset -i LockTime=0 # set default to 0
RETURN_Address=''
# multisig vars
typeset -i msig_reqsigs=0
typeset -i msig_reqkeys=0
typeset -i msig_identifyer=0
typeset -i msig_compressed_pubkeys=0
typeset -i msig_uncompressed_pubkeys=0
msig_cs_pubkeys=''
RAW_TX=''
RAW_TX_Link2Hex="?format=hex"
filename=''
StepCode=''
typeset -i StepCode_decimal=0
typeset -i P2PKH_leading1_cnt=0
address_1st_char=""
address_hash=""
leading_zero=""
address_hash_nb=""
redeemscripthash=""
# and source the global var's config file
. ./tcls.conf
#################################
# procedure to display helptext #
#################################
proc_help() {
echo " "
echo "usage: $0 [-h|-T|-v|-vv] <options>"
echo " -h show this HELP text"
echo " -T use Testnet"
echo " -v display Verbose output"
echo " -vv display VERY Verbose output"
echo " "
echo "Create a transaction from command line where <options> are:"
echo " -c <prevtx_id> <prevtx_output_idx> <prevtx_PKscript | redeem_script>"
echo " <prevtx_amount> <amount> <address> [txfee] [ret_address]"
echo " -f <filename> <amount> <address> [txfee] [ret_address]"
echo " read inputs from a file, use -f help for more details"
echo " -m <n> <m> <comma separated list of pubkeys (66 or 130 hex chars)>"
echo " create a MULTISIG address and corresponding redeem script"
echo " -t <prevtx_id> <prevtx_output_idx>"
echo " <amount> <address> [txfee] [ret_address]"
echo " like -c, but fetch previous pubkey script from blockchain.info"
echo " "
echo " Description of parameters:"
echo " <prevtx_id> : the transaction, from which we want to spend"
echo " <prevtx_output_idx> : output index from previous TX"
echo " <prevtx_PKscript> : (not with '-t') the PK SCRIPT from previous TX"
echo " <redeem_script> : when spending from a P2SH (multisig) TX"
echo " <prevtx_amount> : the amount from previous TX"
echo " <amount> : the amount to spend (decimal, in Satoshi)"
echo " *** careful: input - output = TX fee !!!"
echo " <address> : the target Bitcoin address"
echo " [txfee] : optional tx fee in Satoshis per bytes"
echo " [ret_address] : optional adress for the change"
}
#######################################
# procedure to display verbose output #
#######################################
v_output() {
if [ $Verbose -eq 1 ] ; then
echo "$1"
fi
}
#################################################
# procedure to display even more verbose output #
#################################################
vv_output() {
if [ $VVerbose -eq 1 ] ; then
echo "$1"
fi
}
###########################################################
### check numeric values of utxo_OutPoint and TX_amount ###
###########################################################
chk_numeric() {
if ! expr "$1" : '[0-9]*$'>/dev/null; then
echo " "
echo "*** ERROR: Non numeric parameter $1 for $2."
echo " Please fix. Exiting gracefully ..."
echo " "
exit 1
fi
}
###########################################################
### check that amounts are in the valid bitcoin range ###
###########################################################
chk_min_max() {
if [ $1 -gt $v_in__v_out_max_amount ] || [ $1 -lt 0 ] ; then
echo " "
echo "*** ERROR: $2 ($1) exceeds limits."
echo " Value must be between 1 and 21mio BTC"
echo " exiting gracefully"
echo " "
exit 1
fi
}
###########################################################
### check tx ID (len=32 bytes, only alphanumeric chars ###
###########################################################
chk_tx_ID() {
if [ $VVerbose -eq 1 ]; then
printf " checking length of tx ID (32 hex Bytes=64 alphanumeric chars)"
fi
if [ ${#utxo_TX_ID} -ne 64 ] ; then
echo " "
echo "*** ERROR: expecting a proper formatted Bitcoin TRANSACTION_ID."
echo " Please provide 64 alphanumeric chars (aka 32 hex chars)"
echo " current length: ${#utxo_TX_ID}, utxo_TX_ID:"
echo " $utxo_TX_ID"
echo " "
exit 1
fi
# this seems not to be portable betwenn shell versions ...
# case $utxo_TX_ID in
# *[^a-fA-F0-9]*)
# *[:xdigit]*)
# ;;
# esac
if [ -z "${utxo_TX_ID##*[![:xdigit:]]*}" ] ; then
echo " "
echo "*** ERROR: expecting a proper formatted Bitcoin TRANSACTION_ID."
echo " Please provide 64 alphanumeric chars (aka 32 hex chars [a-fA-F0-9])"
echo " $utxo_TX_ID"
exit 1
fi
if [ $VVerbose -eq 1 ]; then
printf " - ok \n"
fi
}
################################################
# procedure to concatenate string for a raw tx #
################################################
tx_concatenate() {
RAW_TX=$RAW_TX$StepCode
vv_output "$RAW_TX"
vv_output " "
}
##########################################
# procedure to reverse a hex data string #
##########################################
# "s=s substr($0,i,1)" means that substr($0,i,1)
# is appended to the variable s; s=s+something
reverse_hex() {
echo $1 | awk '{ for(i=length;i!=0;i=i-2)s=s substr($0,i-1,2);}END{print s}'
}
###########################################################
# to stay with portable code, use zero padding function ###
###########################################################
zero_pad(){
# zero_pad <string> <length>
[ ${#1} -lt $2 ] && printf "%0$(($2-${#1}))d" ''
printf "%s" "$1"
}
##########################################
# procedure to check for necessary tools #
##########################################
check_tool() {
if [ $VVerbose -eq 1 ]; then
if [ $1 != "http_get_cmd" ] ; then
printf " %-35s" $1
fi
fi
if [ $1 == "http_get_cmd" ] ; then
if [ $OS == "OpenBSD" ] ; then
which ftp > /dev/null
else
which curl > /dev/null
fi
else
which $1 > /dev/null
fi
if [ $? -eq 0 ]; then
if [ $VVerbose -eq 1 ]; then
printf " - yes \n"
fi
else
printf " \n"
echo "*** ERROR: $1 not found, please install $1."
echo "exiting gracefully ..."
exit 1
fi
}
###################################################
### GET_TX_VALUES() - fetch required tx values ###
###################################################
# if param "-t" or "-f" is given, we fetch values from prev transactions.
# This shall be executed:
# ./tcls_tx2txt.sh -vv -r $RAW_TX | grep -A7 TX_OUT[$utxo_OutPoint] > $prawtx_fn
# It would come back with this data, where we can grep / fetch:
#
# 1--> ### TX_OUT[1]
# 000000000001B1FC
# ### TRX Value[1] (uint64_t)
# 2--> hex=FCB1010000000000, reversed_hex=000000000001B1FC, dez=111100, bitcoin=0.00111100
# ### PK_Script Length[1] (var_int)
# 3--> hex=19, dez=25
# 4--> ### pk_script[1] (uchar[])
# 76A9147A8911A06EF9A75A6CB6AF47D72A99A9B6ECB77988AC
# ...
#
# 1--> used to be in the right output ($utxo_OutPoint)
# 2--> used with -f flag, adding up all the amounts
# 3--> used for STEP 5, need to grep and cut
# 4--> used for STEP 6, need to grep -A1 -B1 pk_script[$utxo_OutPoint]
#
get_tx_values() {
vv_output "./tcls_tx2txt.sh -vv -r $RAW_TX | grep -A7 TX_OUT[$utxo_OutPoint] > $prawtx_fn"
./tcls_tx2txt.sh -vv -r $RAW_TX | grep -A7 TX_OUT[[]$utxo_OutPoint[]] > $prawtx_fn
#
# is it better to use grep / cut / tr or a simple awk ???
# awk is 30% faster, and uses only half the system and usr CPU cycles
#
# prev_tx_utxo_amount=$( grep -m1 bitcoin $prawtx_fn | cut -d "=" -f 4 | cut -d "," -f 1 )
# STEP5_SCRIPT_LEN=$( grep -A1 -B1 pk_script $prawtx_fn | head -n1 | cut -b 7,8 )
# STEP6_SCRIPTSIG=$( grep -A1 -B1 pk_script $prawtx_fn | tail -n1 | tr -d "[:space:]" )
#
prev_tx_utxo_amount=$( awk -F "=|," '/bitcoin/ { print $6 }' $prawtx_fn )
chk_min_max $prev_tx_utxo_amount "previous file's tx_utxo_amount"
STEP5_SCRIPT_LEN=$( awk -F ",|=" 'NR==5 { print $2 }' $prawtx_fn )
STEP6_SCRIPTSIG=$( awk '/pk_script/ { getline;print $1}' $prawtx_fn )
RAW_TX=''
vv_output " prev_tx_utxo_amount=$prev_tx_utxo_amount"
vv_output " STEP5_SCRIPT_LEN=$STEP5_SCRIPT_LEN"
vv_output " STEP6_SCRIPTSIG=$STEP6_SCRIPTSIG"
if [ "$prev_tx_utxo_amount" == "" ] && [ "$STEP5_SCRIPT_LEN" == "" ] ; then
echo " "
echo "*** ERROR: inconsistant data from www.blockchain.info"
echo " don't know how to continue without values."
echo " exiting gracefully ... "
exit 1
fi
}
##################################################
# procedure to check even length of address_hash #
##################################################
# https://bitcointalk.org/index.php?topic=1026.0
leading_zeros() {
# get the length of the string h, and if not 'even', add a beginning
# zero. Background: we need to convert the hex characters to a hex value,
# and need to have an even amount of characters...
len=${#address_hash}
s=$(( $len % 2 ))
if [ $s -ne 0 ] ; then
address_hash=$( echo "0$address_hash" )
fi
len=${#address_hash}
# echo "after mod 2 calc, address_hash=$address_hash"
}
##################################################################
# procedure to calculate the checksum (of hex values) of address #
##################################################################
get_chksum() {
# this is not working properly on other UNIXs, made it more portable:
# variable h = address_hash
# chksum_f8=$( xxd -p -r <<<"00$h" |
# openssl dgst -sha256 -binary |
# openssl dgst -sha256 -binary |
# xxd -p -c 80 |
# head -c 8 |
# tr [:lower:] [:upper:] )
#
# This becomes a bit ugly here: we need to convert address_hash to
# hex values, so that openssl can work on it (more precisely: bitcoin
# works with binary data, that is sha256'd). Without "xxd" the use
# of sed will convert data in "\0x00" type hex values, that can be
# written to as file.
# There must be a better way of doing this :-)
#
# vv_output " address_hash before double sha256: $address_hash"
chksum_f8=$( printf "%s" $address_hash_nb | sed 's/[[:xdigit:]]\{2\}/\\x&/g' )
# Step 5 - hash 256
printf $chksum_f8 > tmp_plusnetworkbyte.txt
openssl dgst -sha256 -binary tmp_plusnetworkbyte.txt > tmp_sha256.hex
rm tmp_plusnetworkbyte.txt
# Step 6 - another hash 256
openssl dgst -sha256 -binary tmp_sha256.hex > tmp_dsha256.hex
# Step 7 - get first 4 Bytes (8 chars) as the checksum
chksum_f8=$( od -An -t x1 tmp_dsha256.hex | tr -d [[:blank:]] | tr -d "\n" |
cut -b 1-8 | tr [:lower:] [:upper:] )
}
##################################
### Check bitcoin address hash ###
##################################
# see also here: https://bitcointalk.org/index.php?topic=1543429.0
# bitcoin-tools.sh has this logic, which only works in bash. I changed
# it to be a bit more POISX compliant (also work in ksh).
# in this example variable $1 is the target address
# decodeBase58() {
# echo -n "$1" | sed -e's/^\(1*\).*/\1/' -e's/1/00/g' | tr -d '\n'
# dc -e "$dcr 16o0$(sed 's/./ 58*l&+/g' <<<$1)p" |
# while read n; do echo -n ${n/\\/}; done
# }
#
chk_bc_address_hash() {
echo $TARGET_Address | awk -f tcls_verify_bc_address.awk > /dev/null
if [ $? -ge 1 ] ; then
echo "*** ERROR: invalid address: $s"
echo " exiting gracefully ..."
exit 1
fi
s=$( echo $TARGET_Address | awk -f tcls_verify_bc_address.awk )
vv_output "$s"
s=$( echo $s | sed 's/[0-9]*/ 58*&+ /g' )
vv_output "$s"
# 16o -> base is 16 for output
# | 0d -> duplicate stack
# | | put out all the base58 remainders
# | | | sum everything up and "f" prints the content of the stack
# | | | |
address_hash=$( echo "16o0d $s +f" | dc )
leading_zeros
vv_output " address_hash after leading 0s: $address_hash"
# checksum verification:
# get last 8 chars of address_hash (the reference checksum)
# remove last 8 chars, double sha256 the string,
from=$(( $len - 7 ))
chksum_l8=$( echo $address_hash | cut -b $from-$len )
to=$(( $len - 8 ))
# echo " len=$len, from=$from, to=$to, address_hash=$address_hash"
if [ $to -ne 0 ] ; then
address_hash=$( echo $address_hash | cut -b 1-$to )
vv_output " address_hash without last 8 chars: $address_hash, chksum=$chksum_l8"
else
address_hash=""
fi
# only for P2PKH adresses, verify leading "1s"
# https://bitcointalk.org/index.php?topic=1026.0
# --> each additional leading 1 in an original address needs a "00" hex at the beginning
if [ $T_param_flag -eq 0 ] && [ $msig_identifyer -eq 0 ] ; then
from=2
to=2
address_1st_char=$( echo $TARGET_Address | cut -b $from-$to )
while [ "$address_1st_char" == "1" ]
do
# echo $address_1st_char
leading_zero=$( echo "00$leading_zero" )
from=$(( $from + 1 ))
to=$(( $to + 1 ))
address_1st_char=$( echo $TARGET_Address | cut -b $from-$to )
done
address_hash=$( echo "$leading_zero$address_hash" )
vv_output " address_hash after leading1_cnt: $address_hash"
# fi
# get network bytes in front ... (only for P2PKH addresses?)
# if [ $msig_identifyer -eq 0 ] ; then
# if [ $T_param_flag -eq 0 ] ; then
address_hash_nb=$( echo "00$address_hash" )
# else
# address_hash_nb=$( echo "6f$address_hash" )
# address_hash_nb=$( echo "$address_hash" )
# fi
else
address_hash_nb=$( echo "$address_hash" )
fi
vv_output " address_hash + network byte: $address_hash_nb"
get_chksum
if [ "$chksum_l8" != "$chksum_f8" ] ; then
vv_output " chksum_l8 (last 8 chars): $chksum_l8"
vv_output " chksum_f8 (first 8 chars): $chksum_f8"
echo "*** ERROR: checksum mismatch for target address $TARGET_Address"
echo " * Exiting gracefully..."
exit 1
fi
}
step3to7() {
##############################################################################
### STEP 3 - TX_IN, previous transaction hash: 32hex = 64 chars ###
##############################################################################
v_output "### 3. TX_IN[$line_items], previous transaction hash"
vv_output "### org tx: $utxo_TX_ID"
StepCode=$( reverse_hex $utxo_TX_ID )
vv_output "### reversed: $StepCode"
tx_concatenate
##############################################################################
### STEP 4 - TX_IN, the output index we want to redeem from ###
##############################################################################
v_output "### 4. TX_IN[$line_items], the output index we want to redeem from"
# check that we have a number, not a char...
StepCode=$( echo "obase=16;$utxo_OutPoint"|bc -l)
StepCode=$( zero_pad $StepCode 8 )
StepCode=$( reverse_hex $StepCode )
vv_output "### convert from $utxo_OutPoint to reversed hex: $StepCode"
tx_concatenate
##############################################################################
### STEP 5 - TX_IN, scriptsig length: first hex Byte is length (2 chars) ###
##############################################################################
# For the purpose of signing the transaction, this is temporarily filled
# with the scriptPubKey of the output we want to redeem.
v_output "### 5. TX_IN[$line_items], scriptsig length"
if [ $t_param_flag -eq 0 ] ; then
StepCode=${#utxo_PKScript}
# echo $utxo_PKScript
# echo $StepCode
StepCode=$(( $StepCode / 2 ))
StepCode=$( echo "obase=16;$StepCode"|bc )
if [ ${#StepCode} -eq 1 ] ; then
StepCode=0$StepCode
fi
else
StepCode=$STEP5_SCRIPT_LEN
fi
vv_output "### ScriptSig length=$StepCode"
tx_concatenate
##############################################################################
### STEP 6 - TX_IN, signature script, uchar[] - variable length ###
##############################################################################
# the actual scriptSig (which is the scriptPubKey of the utxo_TX_ID
v_output "### 6. TX_IN[$line_items], signature script"
if [ $t_param_flag -eq 0 ] ; then
StepCode=$utxo_PKScript
vv_output "$StepCode"
else
vv_output "StepCode=$STEP6_SCRIPTSIG"
StepCode=$STEP6_SCRIPTSIG
fi
if [ "$StepCode" == "0" ] ; then
vv_output "$RAW_TX"
vv_output " "
else
tx_concatenate
fi
##############################################################################
### STEP 7 - TX_IN, SEQUENCE: This is currently always set to 0xffffffff ###
##############################################################################
# This is currently always set to 0xffffffff
v_output "### 7. TX_IN[$line_items], concatenate sequence number (currently always 0xffffffff)"
StepCode="ffffffff"
tx_concatenate
}
##############################################################################
### STEP 9 - TX_OUT, TX_amount: a 4 bytes hex (8 chars) for the amount ###
##############################################################################
# a 8-byte reversed hex field, e.g.: 3a01000000000000"
step9() {
v_output "### 9. TX_OUT, tx_out amount (in Satoshis): $amount"
chk_min_max $amount "tx_out amount"
StepCode=$( echo "obase=16;$amount"|bc -l )
StepCode=$( zero_pad $StepCode 16 )
StepCode_rev=$( reverse_hex $StepCode )
vv_output " in hex=$StepCode, reversed=$StepCode_rev"
StepCode=$StepCode_rev
tx_concatenate
}
##############################################################################
### STEP 10 - TX_OUT, LENGTH: Number of bytes in the PK script (var_int) ###
### STEP 11 - TX_OUT, PUBLIC KEY SCRIPT: the OP Codes of the PK script ###
##############################################################################
# convert parameter TARGET_Address to the pubkey script.
# the P2PKH script is preceeded with "76A914" and ends with "88AC".
# the P2SH script is preceeded with "a914" and ends with "87".
##############################################################################
# pubkey script length
step10_11() {
v_output "### 10 & 11. TX_OUT, LENGTH (var_int) and PK Script OpCodes"
# length of P2PKH script (76 A9 14 <20 Bytes> 88 AC) will be 25 Bytes (hex 0x19):
# length of P2SH script (A9 14 <20 Bytes> 87) will be 23 Bytes (hex 0x17)
# when address starts with "1", do P2PKH on main net
# when address starts with "m", do P2PKH on test net
# when address starts with "n", do P2PKH on test net
# when address starts with "2", do P2SH on test net
# when address starts with "3", do P2SH on main net
address_1st_char=$( echo $TARGET_Address | cut -b 1 )
if [ "$address_1st_char" == "2" ] || [ "$address_1st_char" == "3" ] ; then
msig_identifyer=1
fi
chk_bc_address_hash
# observation:
# after base58 decode (chk_bc_address_hash) of a "type 1" address (mainnet),
# the network byte ("00") is automatically removed, whereas others keep the
# network byte. This is due to the "leading 1s check".
# Other addresses need to get the network byte removed, before continuing.
if [ $msig_identifyer -eq 1 ] || [ $T_param_flag -eq 1 ] ; then
address_hash=$( echo $address_hash | cut -b 3-42 )
fi
# first check length of address hash. It is always 20 Bytes (40 chars), in hex 0x14, right?
if [ ${#address_hash} -ne 40 ] ; then
echo "*** ERROR: an address in Bitcoin is always 20 Bytes"
echo "*** check address length. Exiting gracefully ... "
exit 1
fi
redeemscripthash=$address_hash
tmpvar="14"
address_1st_char=$( echo $TARGET_Address | cut -b 1 )
case $address_1st_char in
1) StepCode="19"
StepCode=$( echo $StepCode$OP_DUP$OP_HASH160$tmpvar$address_hash$OP_EQUALVERIFY$OP_CHECKSIG )
;;
2|3) StepCode="17"
StepCode=$( echo $StepCode$OP_HASH160$tmpvar$redeemscripthash$OP_EQUAL )
;;
m|n) T_param_flag=1
StepCode="19"
StepCode=$( echo $StepCode$OP_DUP$OP_HASH160$tmpvar$address_hash$OP_EQUALVERIFY$OP_CHECKSIG )
;;
*) echo "*** ERROR: could not check address type, unrecognized format for $TARGET_Address"
echo " don't know what to do, exiting gracefully ..."
exit
;;
esac
tx_concatenate
}
##########################
### adjust the tx fees ###
##########################
# ... THIS NEEDS FURTHER ANALYSIS !!!
# tx fees are calculated with a tx fee per byte, which is changing...
# Exact length can only be determined during signing process, but here is
# a rough calc:
# if TX_script in this unsigned TX is
# P2PKH (1 input, 1 output), then sig length will be ~227 Bytes
# P2SH can be much longer
# SegWit and MerkleTrees can be much shorter
# on default tx fees, proposal:
# if TX size <= 1000 bytes then use a standard txfee, or manually provided txfee
# if TX size <= 5000 bytes then use standard txfee / 2
# if TX size <= 10000 bytes then use standard txfee / 4
# if TX size <= 100000 bytes then use standard txfee / 8
#
#
# compressed pubkey, tx size = a*148 + b*34 + 10 +/- 1
# uncompressed pubkey, tx size = a*180 + b*34 + 10 +/- 1
# also SegWit:
# ============
# ... how to figure out how much transaction size is allocated to witness data?
# vbytes are calculated by first dividing just the size of the witness data by 4
# and then adding that to the size of the non-witness data.
# see also items I66 and I73 in "todos.txt".
#
# calc_txfee needs to know the length of our RAW_TX
# each input requires later on a signature (length=70 Bytes/140 chars),
# which replaces the existing PKSCRIPT (length 25 Bytes, 50 chars).
# Each input must be signed, so roughly 90 chars signature are added ($std_sig_chars).
# $line_items below is the current TX_IN, so if we have a multi input TX,
# this can be more than 1, and we need a txfee calc for each UTXO
#
# for a later improvement:
# eventually it makes sense, to verify TX_Fee calcs AFTER the signing process?
# just to double check?
#
calc_adjusted_amount() {
a_txfee_per_byte=$txfee_per_byte
echo $RAW_TX > $c_utx_fn
TX_chars=$( wc -c $c_utx_fn | awk '{ print $1 }' )
TX_bytes=$(( $line_items * $std_sig_chars + $TX_chars ))
if [ $TX_bytes -le 1000 ] ; then
a_txfee=$(( $txfee_per_byte * $TX_bytes ))
elif [ $TX_bytes -le 10000 ] ; then
a_txfee_per_byte=$(( $txfee_per_byte / 2 ))
a_txfee=$(( $a_txfee_per_byte * $TX_bytes ))
elif [ $TX_bytes -le 100000 ] ; then
a_txfee_per_byte=$(( $txfee_per_byte / 3 ))
a_txfee=$(( $a_txfee_per_byte * $TX_bytes ))
else
a_txfee_per_byte=$(( $txfee_per_byte / 4 ))
a_txfee=$(( $a_txfee_per_byte $TX_bytes ))
fi
}
#################################################################
### Multisig: create msig address and redeemscript, then exit ###
#################################################################
# validity rules require that the P2SH redeem script is at most 520 bytes.
proc_msig() {
# 0.) verify, that msig_sigs is not greater msig_required_pubkeys
# 1.) convert msig_reqsigs into OP1-OP15 (dez 81-96, hex 0x51-0x60) for redeemscript
# 2.) parse msig_cs_pubkeys, and separate into single public keys
# 3.) verify, that we have amount of $msig_reqkeys in $msig_cs_pubkeys
# 4.) verify each pubkey for validity
# 5.) get each pubkey's length
# 6.) assemble redeemscript (example 2of3)
# <OP_2><len pubkey_A><pubkey_A><len PK_B><PKB><len PK_C><PK_C><OP_3><OP_CHECKMULTISIG>
# 7.) check for these max values:
# msig_redeemscript_maxlen=520
# msig_max_uncompressed_keys=6
# msig_max_compressed_pubkeys=12
# 8.) create P2SH adress from redeem script
# RIPEMD160(SHA256(redeemscript))
# base58_encode("05", redeemscriptHash)
i=0
len_pubkey=0
opcode_msig_reqsigs=0
opcode_msig_reqkeys=0
v_output " msig: required signatures: $msig_reqsigs"
v_output " msig: required keys: $msig_reqkeys"
v_output " msig: comma separated pubkeys: $msig_cs_pubkeys"
# STEP 0: verify, that msig_reqsigs is not greater msig_reqkeys
if [ $msig_reqsigs -gt $msig_reqkeys ] ; then
echo "*** ERROR: required signatures ($msig_reqsigs) must be less or equal required keys ($msig_reqkeys)."
echo " * Exiting gracefully..."
exit 1
fi
# STEP 1: convert msig_reqsigs in OP_Code
# (80 + msig_reqsigs) = Op_code in decimal, convert to hex ...
opcode_msig_reqsigs=$( echo "obase=16;$opcode_numericis_offset+$msig_reqsigs" | bc )
opcode_msig_reqkeys=$( echo "obase=16;$opcode_numericis_offset+$msig_reqkeys" | bc )
redeemscript=$opcode_msig_reqsigs
# STEP 2: verify, that we have amount of $msig_reqkeys in $msig_cs_pubkeys
for pubkey in $(echo $msig_cs_pubkeys | tr "," " "); do
i=$(( $i + 1 ))
done
if [ $i -ne $msig_reqkeys ] ; then
echo "*** Mismatch: comma separated key list does not contain $msig_reqkeys required keys."
echo " * found $i key(s). Exiting gracefully..."
exit 1
else
v_output " msig: found $i of $msig_reqkeys required keys in comma separated key list - good"
fi
# STEP 3: parse msig_cs_pubkeys
for pubkey in $(echo $msig_cs_pubkeys | tr "," " "); do
# STEP 4: verify each pubkey
printf "%s" $pubkey | awk -f tcls_verify_hexkey.awk
if [ $? -gt 0 ] ; then
echo " * Exiting gracefully..."
exit 1
fi
# STEP 5: get each pubkey's length
# echo $pubkey
# printf "%s" $pubkey | wc -c
len_pubkey=$( printf "%s" $pubkey | wc -c )
# compressed pubkeys are $hex_pubkey_compr_len (66)
# uncompressed pubkeys are $hex_pubkey_uncompr_len (130)
if [ $len_pubkey -eq $hex_pubkey_compr_len ] ; then
msig_compressed_pubkeys=$(( msig_compressed_pubkeys + 1 ))
fi
if [ $len_pubkey -eq $hex_pubkey_uncompr_len ] ; then
msig_uncompressed_pubkeys=$(( msig_uncompressed_pubkeys + 1 ))
fi
len_hex=$( echo "obase=16;$len_pubkey/2" | bc )
# STEP 6: assemble redeemscript
redeemscript=$redeemscript$len_hex$pubkey
done
# STEP 7: check against these limits (in tcls.conf):
# msig_redeemscript_maxlen=520
# msig_max_uncompressed_keys=7
# msig_max_compressed_pubkeys=15
# As the redeem script is [m pubkey1 pubkey2 ... n OP_CHECKMULTISIG], it
# follows that the length of all public keys together plus the number of
# public keys must not be over 517. Usually sigs are 73 chars:
# For compressed public keys, this means up to n=15
# m*73 + n*34 <= 496 (up to 1-of-12, 2-of-10, 3-of-8 or 4-of-6).
# For uncompressed ones, up to n=7
# m*73 + n*66 <= 496 (up to 1-of-6, 2-of-5, 3-of-4).
#
# which can be combined to:
# if ($msig_reqsigs * 73bytes) + ($msig_reqkeys * 33bytes) + ($msig_reqkeys * 65bytes) >= 520
#
# echo "$msig_compressed_pubkeys $msig_max_compressed_pubkeys"
if [ $msig_compressed_pubkeys -gt $msig_max_compressed_pubkeys ] ; then
echo "*** compressed pubkeys=$msig_compressed_pubkeys, max=$msig_max_compressed_pubkeys"
echo " length of redeemscr would exceed limits"
echo " Exiting gracefully ... "
echo " "
exit 1
fi
# echo "$msig_uncompressed_pubkeys $msig_max_uncompressed_pubkeys"
if [ $msig_uncompressed_pubkeys -gt $msig_max_uncompressed_pubkeys ] ; then
echo "*** uncompressed pubkeys=$msig_uncompressed_pubkeys, max=$msig_max_uncompressed_pubkeys"
echo " length of redeemscr would exceed limits"
echo " Exiting gracefully ... "
echo " "
exit 1
fi
# printf "(%s * %s / 2) + " $msig_reqsigs $sig_max_length_chars
# printf "(%s * %s / 2) + " $msig_compressed_pubkeys $hex_pubkey_compr_len
# printf "(%s * %s / 2) \n" $msig_uncompressed_pubkeys $hex_pubkey_uncompr_len
len_redeemscr=$(( ($msig_reqsigs * $sig_max_length_chars / 2) + \
($msig_compressed_pubkeys * $hex_pubkey_compr_len / 2) + \
($msig_uncompressed_pubkeys * $hex_pubkey_uncompr_len / 2) ))
# echo "len_redeemscr=$len_redeemscr"
if [ $len_redeemscr -gt $msig_redeemscript_maxlen ] ; then
echo "*** Error: This combination of $msig_reqsigs-of-$msig_reqkeys exceeds limits."
echo " len_redeemscr ($len_redeemscr) will exceed max length ($msig_redeemscript_maxlen)"
echo " Exiting gracefully ... "
echo " "
exit 1
fi
redeemscript=$redeemscript$opcode_msig_reqkeys$OP_CHECKMULTISIG
echo " "
echo "The redeemscript:"
echo "$redeemscript"
echo " "
echo "WARNING: YOU MUST NOT LOSE THE REDEEM SCRIPT, especially"
echo "if you don't have a record of which public keys you used"
echo "to create the P2SH multisig address. You need the redeem"
echo "script to spend any bitcoins sent to the P2SH address."
echo "(https://bitcoin.org/en/developer-examples#p2sh-multisig)"
echo "The redeem script can be recreated with all public keys "
echo "listed in the same order."
echo "HINT: once you've spent from a P2SH address, the redeem "
echo "script is permanently visible in the blockchain."
echo " "
# STEP 8a: RIPEMD160(SHA256(redeemscript))
tmpvar=$( echo $redeemscript | sed 's/[[:xdigit:]]\{2\}/\\x&/g' )
result=$( printf "$tmpvar" | openssl dgst -sha256 | cut -d " " -f 2 )
vv_output "sha256 of redeemscript=$result"
result=$( echo $result | sed 's/[[:xdigit:]]\{2\}/\\x&/g' )
result=$( printf "$result" | openssl dgst -rmd160 | cut -d " " -f 2 )
vv_output "RipeMD of redeemscript=$result"
param=$result
# STEP 8b: base58_encode("05", redeemscriptHash)
echo "The P2SH address:"
if [ $T_param_flag -eq 0 ] ; then ./tcls_base58check_enc.sh -q -p2sh $result; fi
if [ $T_param_flag -eq 1 ] ; then ./tcls_base58check_enc.sh -q -T -p2sh $result; fi
# here we are done with multisig redeem script, we can exit without error :-)
exit 0
}
echo "#########################################################"
echo "### tcls_create.sh: create a raw, unsigned Bitcoin tx ###"
echo "#########################################################"
################################
# command line params handling #
################################
if [ "$1" == "-h" ] ; then
proc_help
exit 0
fi
if [ "$1" == "-f" ] && [ "$2" == "help" ] ; then
echo " provide the following parameters:"
echo " -f <filename> <amount> <address> [txfee] [ret_address]"
echo " <filename>: prev tx params line by line separated by blanks, containing:"
echo " <prev_tx-id> <prev_output-index> <prev_PK-script> <prev_utxo_amount>"
echo " <amount>: amount to spend in Satoshis"
echo " <address>: the target address for this transaction"
echo " [txfee]: numeric amount for tx fees (Satoshi/Byte)"
echo " [ret_address]: a return address"
echo " "
echo " <prev_tx-id> <prev_output-index> <prev_pubkey-script> <prev_utxo_amount>, see:"
echo " blockchain.info/de/unspent?active=<address>"
echo " more detailed with bitcoin core CLI:"
echo " listunspent 6 9999999 \"[\\\"<address>\\\"]\""
echo " 1) fetch only the lines of interest:"
echo " grep -e txid -e vout -e scriptPubKey -e amount bitcoin_cli_utxo.txt > test1"
echo " 2) bring them in record, remove quotes and commas"
echo " awk 'ORS=NR%4?\" \":\"\\\n\" {gsub(/\"|,/, \"\")};1 { print \$2 }' test1 > test2"
echo " 3) convert amount into Satoshis:"
echo " LC_ALL=ISO_8859-1 awk '{ \$NF=\$NF*100000000; print }' test2"
echo " "
echo " *** careful: input - output = tx fee !!!"
echo " "
exit 0
fi
if [ $# -lt 3 ] ; then
echo "insufficient parameter(s) given... "
echo " "
proc_help
exit 0
else
param_count=$#
while [ $# -ge 1 ]
do
case "$1" in
-c)
c_param_flag=1
shift
if [ "$1" == "-f" ] || [ "$1" == "-m" ] || [ "$1" == "-t" ] ; then
echo "*** you cannot use -c with -f or -m or -t at the same time."
echo " Exiting gracefully ... "
exit 1
fi
if [ $# -lt 6 ] ; then
echo "*** you must provide correct number of parameters"
proc_help
exit 1
fi
utxo_TX_ID=$1
chk_tx_ID
shift
chk_numeric $1 utxo_OutPoint
utxo_OutPoint=$1
shift
utxo_PKScript=$1
shift
chk_numeric $1 utxo_Amount
chk_min_max $1 utxo_Amount
utxo_Amount=$1
shift
chk_numeric $1 TX_amount
chk_min_max $1 TX_amount
TX_amount=$1
shift
TARGET_Address=$1
shift
# if there is only one parameter left, it can be tx_fee or return_address
# if length of param is less then 9 chars, then it is for sure tx_fee.
# TX fees shouldn't have 9 digits of satoshis (aka more than a bitcoin)...
# otherwise it is the return address, and txfee needs to get calculated automatically.
if [ $# -eq 1 ] ; then
RETURN_Address=$1
# if length of RETURN_Address is <= 10, then it is the tx_fee ...
if [ ${#RETURN_Address} -lt 10 ] ; then
txfee_param_flag=1
chk_numeric $1 txfee_per_byte
txfee_per_byte=$1
RETURN_Address=''
fi
shift
fi
if [ $# -eq 2 ] ; then
txfee_param_flag=1
chk_numeric $1 txfee_per_byte
chk_min_max $1 txfee_per_byte
txfee_per_byte=$1
RETURN_Address=$2
shift
shift
fi
if [ $# -gt 0 ] ; then
echo "*** already detected last parameter as return address, don't know what to do"
echo " with the following parameter(s). Exiting gracefully ... "
exit 1
fi
;;
-f)
f_param_flag=1
shift
if [ $# -lt 3 ] ; then
echo "*** you must provide correct number of parameters"
proc_help
exit 1
fi
if [ "$1" == "" ] ; then
echo "*** you must provide a FILENAME to the -f parameter!"
exit 1
fi
if [ "$1" == "-c" ] || [ "$1" == "-m" ] || [ "$1" == "-t" ] ; then
echo "*** you cannot use -f with -c or -m or -t at the same time."
echo " Exiting gracefully ... "
exit 1
fi
filename=$1
shift
chk_numeric $1 TX_amount
chk_min_max $1 TX_amount
TX_amount=$1
shift
TARGET_Address=$1
shift
# if there is only one parameter left, it can be tx_fee or return_address
# if length of param is less then 9 chars, then it is for sure tx_fee.
# TX fees shouldn't have 9 digits of satoshis (aka more than a bitcoin)...
# otherwise it is the return address, and txfee needs to get calculated automatically.
if [ $# -eq 1 ] ; then
RETURN_Address=$1
if [ ${#RETURN_Address} -lt 10 ] ; then
txfee_param_flag=1
chk_numeric $1 txfee_per_byte
txfee_per_byte=$1
RETURN_Address=''
fi
shift
fi
if [ $# -eq 2 ] ; then
txfee_param_flag=1
chk_numeric $1 txfee_per_byte
chk_min_max $1 txfee_per_byte
txfee_per_byte=$1
RETURN_Address=$2
shift
shift
fi
if [ $# -gt 0 ] ; then
echo "*** already detected last parameter as return address, don't know what to do"
echo " with the following parameter(s). Exiting gracefully ... "
exit 1
fi
;;
-m)
m_param_flag=1
shift