github.com/Bytom/bytom@v1.1.2-0.20210127130405-ae40204c0b09/protocol/vm/vmutil/builder_test.go (about) 1 package vmutil 2 3 import ( 4 "bytes" 5 "encoding/hex" 6 "testing" 7 8 "github.com/bytom/bytom/protocol/vm" 9 ) 10 11 func TestAddJump(t *testing.T) { 12 cases := []struct { 13 name string 14 wantHex string 15 fn func(t *testing.T, b *Builder) 16 }{ 17 { 18 "single jump single target not yet defined", 19 "630600000061", 20 func(t *testing.T, b *Builder) { 21 target := b.NewJumpTarget() 22 b.AddJump(target) 23 b.AddOp(vm.OP_NOP) 24 b.SetJumpTarget(target) 25 }, 26 }, 27 { 28 "single jump single target already defined", 29 "616300000000", 30 func(t *testing.T, b *Builder) { 31 target := b.NewJumpTarget() 32 b.SetJumpTarget(target) 33 b.AddOp(vm.OP_NOP) 34 b.AddJump(target) 35 }, 36 }, 37 { 38 "two jumps single target not yet defined", 39 "630c00000061630c00000061", 40 func(t *testing.T, b *Builder) { 41 target := b.NewJumpTarget() 42 b.AddJump(target) 43 b.AddOp(vm.OP_NOP) 44 b.AddJump(target) 45 b.AddOp(vm.OP_NOP) 46 b.SetJumpTarget(target) 47 }, 48 }, 49 { 50 "two jumps single target already defined", 51 "616300000000616300000000", 52 func(t *testing.T, b *Builder) { 53 target := b.NewJumpTarget() 54 b.SetJumpTarget(target) 55 b.AddOp(vm.OP_NOP) 56 b.AddJump(target) 57 b.AddOp(vm.OP_NOP) 58 b.AddJump(target) 59 }, 60 }, 61 { 62 "two jumps single target, one not yet defined, one already defined", 63 "630600000061616306000000", 64 func(t *testing.T, b *Builder) { 65 target := b.NewJumpTarget() 66 b.AddJump(target) 67 b.AddOp(vm.OP_NOP) 68 b.SetJumpTarget(target) 69 b.AddOp(vm.OP_NOP) 70 b.AddJump(target) 71 }, 72 }, 73 { 74 "two jumps, two targets, not yet defined", 75 "630c00000061630d0000006161", 76 func(t *testing.T, b *Builder) { 77 target1 := b.NewJumpTarget() 78 b.AddJump(target1) 79 b.AddOp(vm.OP_NOP) 80 target2 := b.NewJumpTarget() 81 b.AddJump(target2) 82 b.AddOp(vm.OP_NOP) 83 b.SetJumpTarget(target1) 84 b.AddOp(vm.OP_NOP) 85 b.SetJumpTarget(target2) 86 }, 87 }, 88 { 89 "two jumps, two targets, already defined", 90 "6161616301000000616302000000", 91 func(t *testing.T, b *Builder) { 92 b.AddOp(vm.OP_NOP) 93 target1 := b.NewJumpTarget() 94 b.SetJumpTarget(target1) 95 b.AddOp(vm.OP_NOP) 96 target2 := b.NewJumpTarget() 97 b.SetJumpTarget(target2) 98 b.AddOp(vm.OP_NOP) 99 b.AddJump(target1) 100 b.AddOp(vm.OP_NOP) 101 b.AddJump(target2) 102 }, 103 }, 104 } 105 for _, c := range cases { 106 t.Run(c.name, func(t *testing.T) { 107 b := NewBuilder() 108 c.fn(t, b) 109 prog, err := b.Build() 110 if err != nil { 111 t.Fatal(err) 112 } 113 want, err := hex.DecodeString(c.wantHex) 114 if err != nil { 115 t.Fatal(err) 116 } 117 if !bytes.Equal(prog, want) { 118 t.Errorf("got %x, want %x", prog, want) 119 } 120 }) 121 } 122 }