ScriptBuilder: if pushing an empty data, use data() not smallNum()

Pushing an empty data is *not* a no-op: an item is added to the
stack. So that empty array should be represented in the data
part of the script chunk.

This makes behaviour consistent with script parsing, and input
signing expects the empty array as a placeholder for a missing
signature.

This reverts 07682145e3 from 2015!

Also adds a test.
This commit is contained in:
Andreas Schildbach 2025-02-06 18:47:11 +01:00
parent f7c7e421fc
commit acd0faaec7
2 changed files with 23 additions and 4 deletions

View file

@ -115,10 +115,7 @@ public class ScriptBuilder {
/** Adds a copy of the given byte array as a data element (i.e. PUSHDATA) at the end of the program. */
public ScriptBuilder data(byte[] data) {
if (data.length == 0)
return smallNum(0);
else
return data(chunks.size(), data);
return data(chunks.size(), data);
}
/** Adds a copy of the given byte array as a data element (i.e. PUSHDATA) at the given index in the program. */

View file

@ -18,14 +18,36 @@ package org.bitcoinj.script;
import org.junit.Test;
import static org.bitcoinj.script.ScriptOpCodes.OP_0;
import static org.bitcoinj.script.ScriptOpCodes.OP_FALSE;
import static org.bitcoinj.script.ScriptOpCodes.OP_TRUE;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
public class ScriptBuilderTest {
@Test
public void emptyPushData() {
Script script = new ScriptBuilder().data(new byte[0]).build();
ScriptChunk chunk = script.chunks().get(0);
assertEquals(OP_0, chunk.opcode);
assertNotNull(chunk.data);
assertEquals(0, chunk.data.length);
byte[] serialized = script.program();
assertArrayEquals(new byte[] {
0x00 // Pushed data
}, serialized);
Script parsedScript = Script.parse(script.program());
ScriptChunk parsedChunk = parsedScript.chunks().get(0);
assertEquals(OP_0, parsedChunk.opcode);
assertNotNull(parsedChunk.data);
assertEquals(0, parsedChunk.data.length);
}
@Test
public void testNumber() {
for (int i = -100; i <= 100; i++) {