ScriptChunk: Fix IllegalArgumentException in toString() for invalid chunks.

Also see https://github.com/bitcoinj/bitcoinj/issues/1860
This commit is contained in:
Matthew Leon 2019-05-19 12:40:21 -04:00 committed by Andreas Schildbach
parent 03f9e94824
commit 0afaaad79a
2 changed files with 16 additions and 11 deletions

View file

@ -152,17 +152,9 @@ public class ScriptChunk {
@Override
public String toString() {
StringBuilder buf = new StringBuilder();
if (isOpCode()) {
buf.append(getOpCodeName(opcode));
} else if (data != null) {
// Data chunk
buf.append(getPushDataName(opcode)).append("[").append(Utils.HEX.encode(data)).append("]");
} else {
// Small num
buf.append(Script.decodeFromOpN(opcode));
}
return buf.toString();
if (data == null)
return getOpCodeName(opcode);
return String.format("%s[%s]", getPushDataName(opcode), Utils.HEX.encode(data));
}
@Override

View file

@ -22,6 +22,7 @@ import static org.bitcoinj.script.ScriptOpCodes.OP_PUSHDATA1;
import static org.bitcoinj.script.ScriptOpCodes.OP_PUSHDATA2;
import static org.bitcoinj.script.ScriptOpCodes.OP_PUSHDATA4;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
@ -43,6 +44,18 @@ public class ScriptChunkTest {
.verify();
}
@Test
public void testToStringOnInvalidScriptChunk() {
// see https://github.com/bitcoinj/bitcoinj/issues/1860
// In summary: toString() throws when given an invalid ScriptChunk.
// It should perhaps be impossible to even construct such a ScriptChunk, but
// until that is the case, toString() should not throw.
ScriptChunk pushWithoutData = new ScriptChunk(OP_PUSHDATA1, null);
// the chunk is invalid, but at least we can determine its opcode
assertEquals("PUSHDATA1", pushWithoutData.toString());
}
@Test
public void testShortestPossibleDataPush() {
assertTrue("empty push", new ScriptBuilder().data(new byte[0]).build().getChunks().get(0)