From 4b441904859275dedbbf449a63a394f64bd7bbe0 Mon Sep 17 00:00:00 2001 From: Evgenii Stratonikov Date: Tue, 17 Mar 2020 15:45:53 +0300 Subject: [PATCH] vm: use truncated division for Integers When divisor is negative, the result is truncated towards zero. --- pkg/vm/vm.go | 2 +- pkg/vm/vm_test.go | 20 +++++++++++++++----- 2 files changed, 16 insertions(+), 6 deletions(-) diff --git a/pkg/vm/vm.go b/pkg/vm/vm.go index 3095bd3c9..10f0341f7 100644 --- a/pkg/vm/vm.go +++ b/pkg/vm/vm.go @@ -776,7 +776,7 @@ func (v *VM) execute(ctx *Context, op opcode.Opcode, parameter []byte) (err erro a := v.estack.Pop().BigInt() v.checkBigIntSize(a) - v.estack.PushVal(new(big.Int).Div(a, b)) + v.estack.PushVal(new(big.Int).Quo(a, b)) case opcode.MUL: a := v.estack.Pop().BigInt() diff --git a/pkg/vm/vm_test.go b/pkg/vm/vm_test.go index de99eeb24..dadd9269b 100644 --- a/pkg/vm/vm_test.go +++ b/pkg/vm/vm_test.go @@ -832,11 +832,21 @@ func TestMULBigResult(t *testing.T) { func TestDiv(t *testing.T) { prog := makeProgram(opcode.DIV) - vm := load(prog) - vm.estack.PushVal(4) - vm.estack.PushVal(2) - runVM(t, vm) - assert.Equal(t, int64(2), vm.estack.Pop().BigInt().Int64()) + runCase := func(p, q, result int64) func(t *testing.T) { + return func(t *testing.T) { + vm := load(prog) + vm.estack.PushVal(p) + vm.estack.PushVal(q) + runVM(t, vm) + assert.Equal(t, result, vm.estack.Pop().BigInt().Int64()) + } + } + + t.Run("positive/positive", runCase(5, 2, 2)) + t.Run("positive/negative", runCase(5, -2, -2)) + t.Run("negative/positive", runCase(-5, 2, -2)) + t.Run("negative/negative", runCase(-5, -2, 2)) + } func TestSub(t *testing.T) {