How to calculate variable length fields?

1

Some parts of bitcoin tx Ex: Script are of variable length var_int. Can someone explain how to calculate its value from that var_int table.

Ex: In the below tx, the bolded part is script-length. its length is supposed to be 349 bytes. When I convert fd5d01 directly to decimal, its value is 16604417. I think I didn't understand var_int table correctly.

01000000013dcd7d87904c9cb7f4b79f36b5a03f96e2e729284c09856238d5353e1182b00200000000fd5d01004730440220762ce7bca626942975bfd5b130ed3470b9f538eb2ac120c2043b445709369628022051d73c80328b543f744aa64b7e9ebefa7ade3e5c716eab4a09b408d2c307ccd701483045022100abf740b58d79cab000f8b0d328c2fff7eb88933971d1b63f8b99e89ca3f2dae602203354770db3cc2623349c87dea7a50cee1f78753141a5052b2d58aeb592bcf50f014cc9524104a882d414e478039cd5b52a92ffb13dd5e6bd4515497439dffd691a0f12af9575fa349b5694ed3155b136f09e63975a1700c9f4d4df849323dac06cf3bd6458cd41046ce31db9bdd543e72fe3039a1f1c047dab87037c36a669ff90e28da1848f640de68c2fe913d363a51154a0c62d7adea1b822d05035077418267b1a1379790187410411ffd36c70776538d079fbae117dc38effafb33304af83ce4894589747aee1ef992f63280567f52f5ba870678b4ab4ff6c8ea600bd217870a8b4f1f09f3a8e8353aeffffffff0130d90000000000001976a914569076ba39fc4ff6a2291d9ea9196d8c08f9c7ab88ac00000000

Can someone explain me the rules from that table?

lch

Posted 2018-03-11T04:18:50.753

Reputation: 183

Answers

1

it's a lot easier, just omit the "fd". Here is the explanation from the bitcoin developers webpages.

Assuming you have the value in an array (tx_array) and a pointer into the array (tx_array_ptr), here is an (unixoide shell script) code example:

# var_int is defined as:
# value         size Format
# < 0xfd        1    uint8_t
# <= 0xffff     3    0xfd + uint16_t
# <= 0xffffffff 5    0xfe + uint32_t
# -             9    0xff + uint64_t 
# if value <= 0xfd, Bytes  = 1
# if value =  0xfd, Bytes  = 2
# if value =  0xfe, Bytes  = 4
# if value =  0xff, Bytes  = 8
  var_int=${tx_array[$tx_array_ptr]}
  if [ "$var_int" == "FD" ] ; then
    tx_array_ptr=$(( $tx_array_ptr + 1 ))
    tx_array_bytes=2
    var_int=$( get_TX_section )
  elif [ "$var_int" == "FE" ] ; then
    tx_array_ptr=$(( $tx_array_ptr + 1 ))
    tx_array_bytes=4
    var_int=$( get_TX_section )
  elif [ "$var_int" == "FF" ] ; then
    tx_array_ptr=$(( $tx_array_ptr + 1 ))
    tx_array_bytes=8
  else
    var_int=${tx_array[$tx_array_ptr]}
  fi

When you have your var_int, don't forget reversing the hex values (big endian conversion)! Then you can send the value e.g. to your decimal converter, so for your value (fd5d01) you get:

  1. omit the "fd"
  2. take the next two bytes "5d01"
  3. big endian conversion "015d"
  4. convert to decimal:

use of "bc" to convert value to decimal:

$ echo "ibase=16;015D" | bc
349

pebwindkraft

Posted 2018-03-11T04:18:50.753

Reputation: 4 568