From 9f5f973d8a41b3f97157939d38479d17b884ce21 Mon Sep 17 00:00:00 2001 From: Nicola Atzei Date: Thu, 26 Oct 2017 15:20:06 +0200 Subject: [PATCH] ScriptBuilder: Fix minimal number encoding for -1. --- .../org/bitcoinj/script/ScriptBuilder.java | 10 +++--- .../bitcoinj/script/ScriptBuilderTest.java | 34 +++++++++++++++++++ 2 files changed, 38 insertions(+), 6 deletions(-) create mode 100644 core/src/test/java/org/bitcoinj/script/ScriptBuilderTest.java diff --git a/core/src/main/java/org/bitcoinj/script/ScriptBuilder.java b/core/src/main/java/org/bitcoinj/script/ScriptBuilder.java index 1d114c56..abe5d586 100644 --- a/core/src/main/java/org/bitcoinj/script/ScriptBuilder.java +++ b/core/src/main/java/org/bitcoinj/script/ScriptBuilder.java @@ -112,11 +112,7 @@ public class ScriptBuilder { * shortest encoding possible. */ public ScriptBuilder number(long num) { - if (num >= 0 && num <= 16) { - return smallNum((int) num); - } else { - return bigNum(num); - } + return number(chunks.size(), num); } /** @@ -124,7 +120,9 @@ public class ScriptBuilder { * uses shortest encoding possible. */ public ScriptBuilder number(int index, long num) { - if (num >= 0 && num <= 16) { + if (num == -1) { + return op(index, OP_1NEGATE); + } else if (num >= 0 && num <= 16) { return smallNum(index, (int) num); } else { return bigNum(index, num); diff --git a/core/src/test/java/org/bitcoinj/script/ScriptBuilderTest.java b/core/src/test/java/org/bitcoinj/script/ScriptBuilderTest.java new file mode 100644 index 00000000..6721e4e5 --- /dev/null +++ b/core/src/test/java/org/bitcoinj/script/ScriptBuilderTest.java @@ -0,0 +1,34 @@ +/* + * Copyright 2017 Nicola Atzei + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.bitcoinj.script; + +import static org.junit.Assert.assertTrue; + +import org.junit.Test; + +public class ScriptBuilderTest { + + @Test + public void testNumber() { + for (int i = -100; i <= 100; i++) { + Script s = new ScriptBuilder().number(i).build(); + for (ScriptChunk ch : s.chunks) { + assertTrue(Integer.toString(i), ch.isShortestPossiblePushData()); + } + } + } +}