From 9eb11d2822b02bd76754f72ef7388fc9b7bb1432 Mon Sep 17 00:00:00 2001 From: BlockChainDev Date: Sat, 16 Mar 2019 21:45:48 +0000 Subject: [PATCH] Make Next() method on Context failable refactor peekContext and Peek --- pkg/vm/stack/context.go | 6 +++--- pkg/vm/stack/invocation.go | 13 ++++++++----- pkg/vm/stack/stack.go | 15 ++++++++++++--- 3 files changed, 23 insertions(+), 11 deletions(-) diff --git a/pkg/vm/stack/context.go b/pkg/vm/stack/context.go index 343800afc..ee6cce1a3 100644 --- a/pkg/vm/stack/context.go +++ b/pkg/vm/stack/context.go @@ -41,12 +41,12 @@ func (c *Context) Context() (*Context, error) { } // Next return the next instruction to execute. -func (c *Context) Next() Instruction { +func (c *Context) Next() (Instruction, error) { c.ip++ if c.ip >= len(c.prog) { - return RET + return RET, errors.New("program pointer is more than the length of program. RETURNING") } - return Instruction(c.prog[c.ip]) + return Instruction(c.prog[c.ip]), nil } // IP returns the absolute instruction without taking 0 into account. diff --git a/pkg/vm/stack/invocation.go b/pkg/vm/stack/invocation.go index 991e28231..a3a66b8ec 100644 --- a/pkg/vm/stack/invocation.go +++ b/pkg/vm/stack/invocation.go @@ -21,11 +21,7 @@ func (i *Invocation) peekContext(n uint16) (*Context, error) { if err != nil { return nil, err } - ctx, err := item.Context() - if err != nil { - return nil, err - } - return ctx, nil + return item.Context() } // CurrentContext returns the current context on the invocation stack @@ -33,6 +29,13 @@ func (i *Invocation) CurrentContext() (*Context, error) { return i.peekContext(0) } +// RemoveCurrentContext removes the context on the top of the invocation stack +// This is a convenience method for Pop +func (i *Invocation) RemoveCurrentContext() error { + _, err := i.Pop() + return err +} + // CallingContext will return the cntext item // that will be called next. func (i *Invocation) CallingContext() (*Context, error) { diff --git a/pkg/vm/stack/stack.go b/pkg/vm/stack/stack.go index a298897e4..e857a9ada 100644 --- a/pkg/vm/stack/stack.go +++ b/pkg/vm/stack/stack.go @@ -106,15 +106,14 @@ func (ras *RandomAccess) Peek(n uint16) (Item, error) { return ras.vals[index], nil } - if ras.vals == nil { - return nil, errors.New("Cannot peak at a nil stack") + if ras.Len() < 1 { + return nil, fmt.Errorf("cannot peak at a stack with no item, length of stack is %d", ras.Len()) } // Check that we are not peeking out of the bounds if n > stackSize-1 { return nil, fmt.Errorf("Tried to peek at index %d when length of stack is %d", n, len(ras.vals)) } - index := stackSize - n - 1 return ras.vals[index], nil @@ -131,3 +130,13 @@ func (ras *RandomAccess) PopInt() (*Int, error) { } return item.Integer() } + +// PopByteArray will remove the last stack item that was added +// And cast it to an ByteArray +func (ras *RandomAccess) PopByteArray() (*ByteArray, error) { + item, err := ras.Pop() + if err != nil { + return nil, err + } + return item.ByteArray() +}