segregated witness – How does the SegWit a part of a transaction get serialized and parsed?

0
53


I am studying Programming Bitcoin. And in Chapter13, I’m confused with how the witness half is serialized and parsed. The auther provides the next technique to parse it:

def parse_segwit(cls, s, testnet=False):
    model = little_endian_to_int(s.learn(4))
    marker = s.learn(2)
    if marker != b'x00x01':  
        increase RuntimeError('Not a segwit transaction {}'.format(marker))
    num_inputs = read_varint(s)
    inputs = []
    for _ in vary(num_inputs):
        inputs.append(TxIn.parse(s))
    num_outputs = read_varint(s)
    outputs = []
    for _ in vary(num_outputs):
        outputs.append(TxOut.parse(s))
    for tx_in in inputs:  
        num_items = read_varint(s)
        objects = []
        for _ in vary(num_items):
            item_len = read_varint(s)
            if item_len == 0:        # the place I am unable to perceive 
                objects.append(0)      #
            else:
                objects.append(s.learn(item_len))
        tx_in.witness = objects
    locktime = little_endian_to_int(s.learn(4))
    return cls(model, inputs, outputs, locktime, 
               testnet=testnet, segwit=True)

And the next code to serialize it:

def serialize_segwit(self):
    end result = int_to_little_endian(self.model, 4)
    end result += b'x00x01'  
    end result += encode_varint(len(self.tx_ins))
    for tx_in in self.tx_ins:
        end result += tx_in.serialize()
    end result += encode_varint(len(self.tx_outs))
    for tx_out in self.tx_outs:
        end result += tx_out.serialize()
    for tx_in in self.tx_ins:  
        end result += int_to_little_endian(len(tx_in.witness), 1)
        for merchandise in tx_in.witness:
            if sort(merchandise) == int:
                end result += int_to_little_endian(merchandise, 1)
            else:
                end result += encode_varint(len(merchandise)) + merchandise
    end result += int_to_little_endian(self.locktime, 4)
    return end result

What I am unable to perceive are the final for loops in each strategies. In my understanding, these are the place segwit half get serialized and deserialized, and these codes must be in one-to-one correspondence. As they do within the first half half. However they do not match within the for loops of the final half half. I imply:

  • For “num_items = read_varint(s)”, there must be a “end result += encode_varint(len(tx_in.witness))”.
  • For “item_len = read_varint(s)”, there must be a “end result += encode_varint(len(merchandise))”.
  • And for “if item_len == 0:”, I do not know what this if do and the place the corresponding serialization logic is.

So is something improper with my understanding of the segwit half logic?

LEAVE A REPLY

Please enter your comment!
Please enter your name here