@Override
    public int messageSize() {
        boolean useSegwit = hasWitnesses() && allowWitness(protocolVersion);
        int size = 4; // version
        if (useSegwit)
            size += 2; // marker, flag
        size += VarInt.sizeOf(inputs.size());
        for (TransactionInput in : inputs)
            size += in.messageSize();
        size += VarInt.sizeOf(outputs.size());
        for (TransactionOutput out : outputs)
            size += out.messageSize();
        if (useSegwit)
            for (TransactionInput in : inputs)
                size += in.getWitness().messageSize();
        size += 4; // locktime
        return size;
    }
@Test
    public void testMessageSize() {
        Transaction tx = new Transaction();
        int length = tx.messageSize();

        // add fake transaction input
        TransactionInput input = new TransactionInput(null, ScriptBuilder.createEmpty().program(),
                new TransactionOutPoint(0, Sha256Hash.ZERO_HASH));
        tx.addInput(input);
        length += input.messageSize();

        // add fake transaction output
        TransactionOutput output = new TransactionOutput(null, Coin.COIN, ADDRESS);
        tx.addOutput(output);
        length += output.messageSize();

        // message size has now grown
        assertEquals(length, tx.messageSize());
    }