10 chainjson "github.com/bytom/encoding/json"
11 "github.com/bytom/errors"
12 "github.com/bytom/protocol/vm"
13 "github.com/bytom/protocol/vm/vmutil"
16 // ValueInfo describes how a blockchain value is used in a contract
18 type ValueInfo struct {
19 // Name is the clause's name for this value.
20 Name string `json:"name"`
22 // Program is the program expression used to the lock the value, if
23 // the value is locked with "lock." If it's unlocked with "unlock"
24 // instead, this is empty.
25 Program string `json:"program,omitempty"`
27 // Asset is the expression describing the asset type the value must
28 // have, as it appears in a clause's "requires" section. If this is
29 // the contract value instead, this is empty.
30 Asset string `json:"asset,omitempty"`
32 // Amount is the expression describing the amount the value must
33 // have, as it appears in a clause's "requires" section. If this is
34 // the contract value instead, this is empty.
35 Amount string `json:"amount,omitempty"`
38 // ContractArg is an argument with which to instantiate a contract as
39 // a program. Exactly one of B, I, and S should be supplied.
40 type ContractArg struct {
41 B *bool `json:"boolean,omitempty"`
42 I *int64 `json:"integer,omitempty"`
43 S *chainjson.HexBytes `json:"string,omitempty"`
46 // Compile parses a sequence of Equity contracts from the supplied reader
47 // and produces Contract objects containing the compiled bytecode and
48 // other analysis. If argMap is non-nil, it maps contract names to
49 // lists of arguments with which to instantiate them as programs, with
50 // the results placed in the contract's Program field. A contract
51 // named in argMap but not found in the input is silently ignored.
52 func Compile(r io.Reader) ([]*Contract, error) {
53 inp, err := ioutil.ReadAll(r)
55 return nil, errors.Wrap(err, "reading input")
57 contracts, err := parse(inp)
59 return nil, errors.Wrap(err, "parse error")
62 globalEnv := newEnviron(nil)
63 for _, k := range keywords {
64 globalEnv.add(k, nilType, roleKeyword)
66 for _, b := range builtins {
67 globalEnv.add(b.name, nilType, roleBuiltin)
70 // All contracts must be checked for recursiveness before any are
72 for _, contract := range contracts {
73 contract.Recursive = checkRecursive(contract)
76 for _, contract := range contracts {
77 err = globalEnv.addContract(contract)
83 for _, contract := range contracts {
84 err = compileContract(contract, globalEnv)
86 return nil, errors.Wrap(err, "compiling contract")
88 for _, clause := range contract.Clauses {
89 for _, stmt := range clause.statements {
90 switch s := stmt.(type) {
92 valueInfo := ValueInfo{
93 Amount: s.lockedAmount.String(),
94 Asset: s.lockedAsset.String(),
95 Program: s.program.String(),
98 clause.Values = append(clause.Values, valueInfo)
99 case *unlockStatement:
100 valueInfo := ValueInfo{
101 Amount: contract.Value.Amount,
102 Asset: contract.Value.Asset,
104 clause.Values = append(clause.Values, valueInfo)
110 return contracts, nil
113 func Instantiate(body []byte, params []*Param, recursive bool, args []ContractArg) ([]byte, error) {
114 if len(args) != len(params) {
115 return nil, fmt.Errorf("got %d argument(s), want %d", len(args), len(params))
118 // typecheck args against param types
119 for i, param := range params {
122 case amountType, intType:
124 return nil, fmt.Errorf("type mismatch in arg %d (want integer)", i)
126 case assetType, hashType, progType, pubkeyType, sigType, strType:
128 return nil, fmt.Errorf("type mismatch in arg %d (want string)", i)
132 return nil, fmt.Errorf("type mismatch in arg %d (want boolean)", i)
137 b := vmutil.NewBuilder()
139 for i := len(args) - 1; i >= 0; i-- {
156 // <argN> <argN-1> ... <arg1> <body> DEPTH OVER 0 CHECKPREDICATE
158 b.AddOp(vm.OP_DEPTH).AddOp(vm.OP_OVER)
160 // <argN> <argN-1> ... <arg1> DEPTH <body> 0 CHECKPREDICATE
165 b.AddOp(vm.OP_CHECKPREDICATE)
169 func compileContract(contract *Contract, globalEnv *environ) error {
172 if len(contract.Clauses) == 0 {
173 return fmt.Errorf("empty contract")
175 env := newEnviron(globalEnv)
176 for _, p := range contract.Params {
177 err = env.add(p.Name, p.Type, roleContractParam)
183 // value is spilt with valueAmount and valueAsset
184 if err = env.add(contract.Value.Amount, amountType, roleContractValue); err != nil {
187 if err = env.add(contract.Value.Asset, assetType, roleContractValue); err != nil {
191 for _, c := range contract.Clauses {
192 err = env.add(c.Name, nilType, roleClause)
198 err = prohibitSigParams(contract)
202 err = requireAllParamsUsedInClauses(contract.Params, contract.Clauses)
209 if len(contract.Clauses) > 1 {
210 stk = stk.add("<clause selector>")
213 for i := len(contract.Params) - 1; i >= 0; i-- {
214 p := contract.Params[i]
215 stk = stk.add(p.Name)
218 if contract.Recursive {
219 stk = stk.add(contract.Name)
224 if len(contract.Clauses) == 1 {
225 err = compileClause(b, stk, contract, env, contract.Clauses[0])
230 if len(contract.Params) > 0 {
231 // A clause selector is at the bottom of the stack. Roll it to the
233 n := len(contract.Params)
234 if contract.Recursive {
237 stk = b.addRoll(stk, n) // stack: [<clause params> <contract params> [<maybe contract body>] <clause selector>]
243 for i := len(contract.Clauses) - 1; i >= 2; i-- {
244 stk = b.addDup(stk) // stack: [... <clause selector> <clause selector>]
245 stk = b.addInt64(stk, int64(i)) // stack: [... <clause selector> <clause selector> <i>]
246 stk = b.addNumEqual(stk, fmt.Sprintf("(<clause selector> == %d)", i)) // stack: [... <clause selector> <i == clause selector>]
247 stk = b.addJumpIf(stk, contract.Clauses[i].Name) // stack: [... <clause selector>]
248 stk2 = stk // stack starts here for clauses 2 through N-1
252 stk = b.addJumpIf(stk, contract.Clauses[1].Name) // consumes the clause selector
254 // no jump needed for clause 0
256 for i, clause := range contract.Clauses {
258 // Clauses 0 and 1 have no clause selector on top of the
259 // stack. Clauses 2 and later do.
263 b.addJumpTarget(stk, clause.Name)
269 err = compileClause(b, stk, contract, env, clause)
271 return errors.Wrapf(err, "compiling clause \"%s\"", clause.Name)
273 b.forgetPendingVerify()
274 if i < len(contract.Clauses)-1 {
275 b.addJump(stk, "_end")
278 b.addJumpTarget(stk, "_end")
281 opcodes := optimize(b.opcodes())
282 prog, err := vm.Assemble(opcodes)
288 contract.Opcodes = opcodes
290 contract.Steps = b.steps()
295 func compileClause(b *builder, contractStk stack, contract *Contract, env *environ, clause *Clause) error {
298 // copy env to leave outerEnv unchanged
299 env = newEnviron(env)
300 for _, p := range clause.Params {
301 err = env.add(p.Name, p.Type, roleClauseParam)
306 assignIndexes(clause)
309 for _, p := range clause.Params {
310 // NOTE: the order of clause params is not reversed, unlike
311 // contract params (and also unlike the arguments to Equity
313 stk = stk.add(p.Name)
315 stk = stk.addFromStack(contractStk)
317 // a count of the number of times each variable is referenced
318 counts := make(map[string]int)
319 for _, s := range clause.statements {
320 s.countVarRefs(counts)
323 for _, s := range clause.statements {
324 switch stmt := s.(type) {
325 case *verifyStatement:
326 stk, err = compileExpr(b, stk, contract, clause, env, counts, stmt.expr)
328 return errors.Wrapf(err, "in verify statement in clause \"%s\"", clause.Name)
330 stk = b.addVerify(stk)
332 // special-case reporting of certain function calls
333 if c, ok := stmt.expr.(*callExpr); ok && len(c.args) == 1 {
334 if b := referencedBuiltin(c.fn); b != nil {
337 clause.BlockHeight = append(clause.BlockHeight, c.args[0].String())
339 clause.BlockHeight = append(clause.BlockHeight, c.args[0].String())
346 stk = b.addInt64(stk, stmt.index)
348 // TODO: permit more complex expressions for locked,
349 // like "lock x+y with foo" (?)
351 if stmt.lockedAmount.String() == contract.Value.Amount && stmt.lockedAsset.String() == contract.Value.Asset {
352 stk = b.addAmount(stk, contract.Value.Amount)
353 stk = b.addAsset(stk, contract.Value.Asset)
355 if strings.Contains(stmt.lockedAmount.String(), contract.Value.Amount) {
356 stk = b.addAmount(stk, contract.Value.Amount)
359 if strings.Contains(stmt.lockedAsset.String(), contract.Value.Asset) {
360 stk = b.addAsset(stk, contract.Value.Asset)
364 stk, err = compileExpr(b, stk, contract, clause, env, counts, stmt.lockedAmount)
366 return errors.Wrapf(err, "in lock statement in clause \"%s\"", clause.Name)
370 stk, err = compileExpr(b, stk, contract, clause, env, counts, stmt.lockedAsset)
372 return errors.Wrapf(err, "in lock statement in clause \"%s\"", clause.Name)
377 stk = b.addInt64(stk, 1)
380 stk, err = compileExpr(b, stk, contract, clause, env, counts, stmt.program)
382 return errors.Wrapf(err, "in lock statement in clause \"%s\"", clause.Name)
385 stk = b.addCheckOutput(stk, fmt.Sprintf("checkOutput(%s, %s, %s)",
386 stmt.lockedAmount.String(), stmt.lockedAsset.String(), stmt.program))
387 stk = b.addVerify(stk)
389 case *unlockStatement:
390 if len(clause.statements) == 1 {
391 // This is the only statement in the clause, make sure TRUE is
393 stk = b.addBoolean(stk, true)
398 err = requireAllValuesDisposedOnce(contract, clause)
402 err = typeCheckClause(contract, clause, env)
406 err = requireAllParamsUsedInClause(clause.Params, clause)
414 func compileExpr(b *builder, stk stack, contract *Contract, clause *Clause, env *environ, counts map[string]int, expr expression) (stack, error) {
417 switch e := expr.(type) {
419 // Do typechecking after compiling subexpressions (because other
420 // compilation errors are more interesting than type mismatch
423 stk, err = compileExpr(b, stk, contract, clause, env, counts, e.left)
425 return stk, errors.Wrapf(err, "in left operand of \"%s\" expression", e.op.op)
427 stk, err = compileExpr(b, stk, contract, clause, env, counts, e.right)
429 return stk, errors.Wrapf(err, "in right operand of \"%s\" expression", e.op.op)
432 lType := e.left.typ(env)
433 if e.op.left != "" && !(lType == e.op.left || lType == amountType) {
434 return stk, fmt.Errorf("in \"%s\", left operand has type \"%s\", must be \"%s\"", e, lType, e.op.left)
437 rType := e.right.typ(env)
438 if e.op.right != "" && !(rType == e.op.right || rType == amountType) {
439 return stk, fmt.Errorf("in \"%s\", right operand has type \"%s\", must be \"%s\"", e, rType, e.op.right)
445 // Maybe one is Hash and the other is (more-specific-Hash subtype).
446 // TODO(bobg): generalize this mechanism
447 if lType == hashType && isHashSubtype(rType) {
448 propagateType(contract, clause, env, rType, e.left)
449 } else if rType == hashType && isHashSubtype(lType) {
450 propagateType(contract, clause, env, lType, e.right)
452 return stk, fmt.Errorf("type mismatch in \"%s\": left operand has type \"%s\", right operand has type \"%s\"", e, lType, rType)
455 if lType == "Boolean" {
456 return stk, fmt.Errorf("in \"%s\": using \"%s\" on Boolean values not allowed", e, e.op.op)
460 stk = b.addOps(stk.dropN(2), e.op.opcodes, e.String())
463 // Do typechecking after compiling subexpression (because other
464 // compilation errors are more interesting than type mismatch
468 stk, err = compileExpr(b, stk, contract, clause, env, counts, e.expr)
470 return stk, errors.Wrapf(err, "in \"%s\" expression", e.op.op)
473 if e.op.operand != "" && e.expr.typ(env) != e.op.operand {
474 return stk, fmt.Errorf("in \"%s\", operand has type \"%s\", must be \"%s\"", e, e.expr.typ(env), e.op.operand)
476 b.addOps(stk.drop(), e.op.opcodes, e.String())
479 bi := referencedBuiltin(e.fn)
481 if v, ok := e.fn.(varRef); ok {
482 if entry := env.lookup(string(v)); entry != nil && entry.t == contractType {
483 clause.Contracts = append(clause.Contracts, entry.c.Name)
485 partialName := fmt.Sprintf("%s(...)", v)
486 stk = b.addData(stk, nil)
488 if len(e.args) != len(entry.c.Params) {
489 return stk, fmt.Errorf("contract \"%s\" expects %d argument(s), got %d", entry.c.Name, len(entry.c.Params), len(e.args))
492 for i := len(e.args) - 1; i >= 0; i-- {
494 if entry.c.Params[i].Type != "" && arg.typ(env) != entry.c.Params[i].Type {
495 return stk, fmt.Errorf("argument %d to contract \"%s\" has type \"%s\", must be \"%s\"", i, entry.c.Name, arg.typ(env), entry.c.Params[i].Type)
497 stk, err = compileExpr(b, stk, contract, clause, env, counts, arg)
501 stk = b.addCatPushdata(stk, partialName)
505 case entry.c == contract:
506 // Recursive call - cannot use entry.c.Body
507 // <argN> <argN-1> ... <arg1> <body> DEPTH OVER 0 CHECKPREDICATE
508 stk, err = compileRef(b, stk, counts, varRef(contract.Name))
510 return stk, errors.Wrap(err, "compiling contract call")
512 stk = b.addCatPushdata(stk, partialName)
513 stk = b.addData(stk, []byte{byte(vm.OP_DEPTH), byte(vm.OP_OVER)})
514 stk = b.addCat(stk, partialName)
516 case entry.c.Recursive:
517 // Non-recursive call to a (different) recursive contract
518 // <argN> <argN-1> ... <arg1> <body> DEPTH OVER 0 CHECKPREDICATE
519 if len(entry.c.Body) == 0 {
520 // TODO(bobg): sort input contracts topologically to permit forward calling
521 return stk, fmt.Errorf("contract \"%s\" not defined", entry.c.Name)
523 stk = b.addData(stk, entry.c.Body)
524 stk = b.addCatPushdata(stk, partialName)
525 stk = b.addData(stk, []byte{byte(vm.OP_DEPTH), byte(vm.OP_OVER)})
526 stk = b.addCat(stk, partialName)
529 // Non-recursive call to non-recursive contract
530 // <argN> <argN-1> ... <arg1> DEPTH <body> 0 CHECKPREDICATE
531 stk = b.addData(stk, []byte{byte(vm.OP_DEPTH)})
532 stk = b.addCat(stk, partialName)
533 if len(entry.c.Body) == 0 {
534 // TODO(bobg): sort input contracts topologically to permit forward calling
535 return stk, fmt.Errorf("contract \"%s\" not defined", entry.c.Name)
537 stk = b.addData(stk, entry.c.Body)
538 stk = b.addCatPushdata(stk, partialName)
540 stk = b.addData(stk, vm.Int64Bytes(0))
541 stk = b.addCatPushdata(stk, partialName)
542 stk = b.addData(stk, []byte{byte(vm.OP_CHECKPREDICATE)})
543 stk = b.addCat(stk, e.String())
548 return stk, fmt.Errorf("unknown function \"%s\"", e.fn)
551 if len(e.args) != len(bi.args) {
552 return stk, fmt.Errorf("wrong number of args for \"%s\": have %d, want %d", bi.name, len(e.args), len(bi.args))
555 // WARNING WARNING WOOP WOOP
557 // WARNING WARNING WOOP WOOP
558 if bi.name == "checkTxMultiSig" {
559 if _, ok := e.args[0].(listExpr); !ok {
560 return stk, fmt.Errorf("checkTxMultiSig expects list literals, got %T for argument 0", e.args[0])
562 if _, ok := e.args[1].(listExpr); !ok {
563 return stk, fmt.Errorf("checkTxMultiSig expects list literals, got %T for argument 1", e.args[1])
568 stk, k1, err = compileArg(b, stk, contract, clause, env, counts, e.args[1])
573 // stack: [... sigM ... sig1 M]
576 stk, altEntry = b.addToAltStack(stk) // stack: [... sigM ... sig1]
577 stk = b.addTxSigHash(stk) // stack: [... sigM ... sig1 txsighash]
579 stk, k2, err = compileArg(b, stk, contract, clause, env, counts, e.args[0])
584 // stack: [... sigM ... sig1 txsighash pubkeyN ... pubkey1 N]
586 stk = b.addFromAltStack(stk, altEntry) // stack: [... sigM ... sig1 txsighash pubkeyN ... pubkey1 N M]
587 stk = b.addSwap(stk) // stack: [... sigM ... sig1 txsighash pubkeyN ... pubkey1 M N]
588 stk = b.addCheckMultisig(stk, k1+k2, e.String())
595 for i := len(e.args) - 1; i >= 0; i-- {
599 stk, k2, err = compileArg(b, stk, contract, clause, env, counts, a)
601 return stk, errors.Wrapf(err, "compiling argument %d in call expression", i)
606 // Do typechecking after compiling subexpressions (because other
607 // compilation errors are more interesting than type mismatch
609 for i, actual := range e.args {
610 if bi.args[i] != "" && actual.typ(env) != bi.args[i] {
611 return stk, fmt.Errorf("argument %d to \"%s\" has type \"%s\", must be \"%s\"", i, bi.name, actual.typ(env), bi.args[i])
615 stk = b.addOps(stk.dropN(k), bi.opcodes, e.String())
617 // special-case reporting
619 case "sha3", "sha256":
620 clause.HashCalls = append(clause.HashCalls, HashCall{bi.name, e.args[0].String(), string(e.args[0].typ(env))})
624 return compileRef(b, stk, counts, e)
627 stk = b.addInt64(stk, int64(e))
630 stk = b.addData(stk, []byte(e))
633 stk = b.addBoolean(stk, bool(e))
636 // Lists are excluded here because they disobey the invariant of
637 // this function: namely, that it increases the stack size by
638 // exactly one. (A list pushes its items and its length on the
639 // stack.) But they're OK as function-call arguments because the
640 // function (presumably) consumes all the stack items added.
641 return stk, fmt.Errorf("encountered list outside of function-call context")
646 func compileArg(b *builder, stk stack, contract *Contract, clause *Clause, env *environ, counts map[string]int, expr expression) (stack, int, error) {
648 if list, ok := expr.(listExpr); ok {
649 for i := 0; i < len(list); i++ {
650 elt := list[len(list)-i-1]
652 stk, err = compileExpr(b, stk, contract, clause, env, counts, elt)
658 stk = b.addInt64(stk, int64(len(list)))
663 stk, err = compileExpr(b, stk, contract, clause, env, counts, expr)
667 func compileRef(b *builder, stk stack, counts map[string]int, ref varRef) (stack, error) {
668 depth := stk.find(string(ref))
670 return stk, fmt.Errorf("undefined reference: \"%s\"", ref)
674 if count, ok := counts[string(ref)]; ok && count > 0 {
676 counts[string(ref)] = count
693 stk = b.addRoll(stk, depth)
695 stk = b.addPick(stk, depth)
701 func (a *ContractArg) UnmarshalJSON(b []byte) error {
702 var m map[string]json.RawMessage
703 err := json.Unmarshal(b, &m)
707 if r, ok := m["boolean"]; ok {
709 err = json.Unmarshal(r, &bval)
716 if r, ok := m["integer"]; ok {
718 err = json.Unmarshal(r, &ival)
727 return fmt.Errorf("contract arg must define one of boolean, integer, string")
729 var sval chainjson.HexBytes
730 err = json.Unmarshal(r, &sval)