You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

372 lines
12 KiB

10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
  1. package types
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "io"
  6. "github.com/tendermint/tendermint/Godeps/_workspace/src/golang.org/x/crypto/ripemd160"
  7. acm "github.com/tendermint/tendermint/account"
  8. . "github.com/tendermint/tendermint/common"
  9. ptypes "github.com/tendermint/tendermint/permission/types"
  10. "github.com/tendermint/tendermint/wire"
  11. )
  12. var (
  13. ErrTxInvalidAddress = errors.New("Error invalid address")
  14. ErrTxDuplicateAddress = errors.New("Error duplicate address")
  15. ErrTxInvalidAmount = errors.New("Error invalid amount")
  16. ErrTxInsufficientFunds = errors.New("Error insufficient funds")
  17. ErrTxInsufficientGasPrice = errors.New("Error insufficient gas price")
  18. ErrTxUnknownPubKey = errors.New("Error unknown pubkey")
  19. ErrTxInvalidPubKey = errors.New("Error invalid pubkey")
  20. ErrTxInvalidSignature = errors.New("Error invalid signature")
  21. ErrTxInvalidString = errors.New("Error invalid string")
  22. ErrTxPermissionDenied = errors.New("Error permission denied")
  23. )
  24. type ErrTxInvalidSequence struct {
  25. Got int
  26. Expected int
  27. }
  28. func (e ErrTxInvalidSequence) Error() string {
  29. return Fmt("Error invalid sequence. Got %d, expected %d", e.Got, e.Expected)
  30. }
  31. /*
  32. Tx (Transaction) is an atomic operation on the ledger state.
  33. Account Txs:
  34. - SendTx Send coins to address
  35. - CallTx Send a msg to a contract that runs in the vm
  36. - NameTx Store some value under a name in the global namereg
  37. Validation Txs:
  38. - BondTx New validator posts a bond
  39. - UnbondTx Validator leaves
  40. - DupeoutTx Validator dupes out (equivocates)
  41. Admin Txs:
  42. - PermissionsTx
  43. */
  44. type Tx interface {
  45. WriteSignBytes(chainID string, w io.Writer, n *int64, err *error)
  46. }
  47. // Types of Tx implementations
  48. const (
  49. // Account transactions
  50. TxTypeSend = byte(0x01)
  51. TxTypeCall = byte(0x02)
  52. TxTypeName = byte(0x03)
  53. // Validation transactions
  54. TxTypeBond = byte(0x11)
  55. TxTypeUnbond = byte(0x12)
  56. TxTypeRebond = byte(0x13)
  57. TxTypeDupeout = byte(0x14)
  58. // Admin transactions
  59. TxTypePermissions = byte(0x20)
  60. )
  61. // for wire.readReflect
  62. var _ = wire.RegisterInterface(
  63. struct{ Tx }{},
  64. wire.ConcreteType{&SendTx{}, TxTypeSend},
  65. wire.ConcreteType{&CallTx{}, TxTypeCall},
  66. wire.ConcreteType{&NameTx{}, TxTypeName},
  67. wire.ConcreteType{&BondTx{}, TxTypeBond},
  68. wire.ConcreteType{&UnbondTx{}, TxTypeUnbond},
  69. wire.ConcreteType{&RebondTx{}, TxTypeRebond},
  70. wire.ConcreteType{&DupeoutTx{}, TxTypeDupeout},
  71. wire.ConcreteType{&PermissionsTx{}, TxTypePermissions},
  72. )
  73. //-----------------------------------------------------------------------------
  74. type TxInput struct {
  75. Address []byte `json:"address"` // Hash of the PubKey
  76. Amount int64 `json:"amount"` // Must not exceed account balance
  77. Sequence int `json:"sequence"` // Must be 1 greater than the last committed TxInput
  78. Signature acm.Signature `json:"signature"` // Depends on the PubKey type and the whole Tx
  79. PubKey acm.PubKey `json:"pub_key"` // Must not be nil, may be nil
  80. }
  81. func (txIn *TxInput) ValidateBasic() error {
  82. if len(txIn.Address) != 20 {
  83. return ErrTxInvalidAddress
  84. }
  85. if txIn.Amount == 0 {
  86. return ErrTxInvalidAmount
  87. }
  88. return nil
  89. }
  90. func (txIn *TxInput) WriteSignBytes(w io.Writer, n *int64, err *error) {
  91. wire.WriteTo([]byte(Fmt(`{"address":"%X","amount":%v,"sequence":%v}`, txIn.Address, txIn.Amount, txIn.Sequence)), w, n, err)
  92. }
  93. func (txIn *TxInput) String() string {
  94. return Fmt("TxInput{%X,%v,%v,%v,%v}", txIn.Address, txIn.Amount, txIn.Sequence, txIn.Signature, txIn.PubKey)
  95. }
  96. //-----------------------------------------------------------------------------
  97. type TxOutput struct {
  98. Address []byte `json:"address"` // Hash of the PubKey
  99. Amount int64 `json:"amount"` // The sum of all outputs must not exceed the inputs.
  100. }
  101. func (txOut *TxOutput) ValidateBasic() error {
  102. if len(txOut.Address) != 20 {
  103. return ErrTxInvalidAddress
  104. }
  105. if txOut.Amount == 0 {
  106. return ErrTxInvalidAmount
  107. }
  108. return nil
  109. }
  110. func (txOut *TxOutput) WriteSignBytes(w io.Writer, n *int64, err *error) {
  111. wire.WriteTo([]byte(Fmt(`{"address":"%X","amount":%v}`, txOut.Address, txOut.Amount)), w, n, err)
  112. }
  113. func (txOut *TxOutput) String() string {
  114. return Fmt("TxOutput{%X,%v}", txOut.Address, txOut.Amount)
  115. }
  116. //-----------------------------------------------------------------------------
  117. type SendTx struct {
  118. Inputs []*TxInput `json:"inputs"`
  119. Outputs []*TxOutput `json:"outputs"`
  120. }
  121. func (tx *SendTx) WriteSignBytes(chainID string, w io.Writer, n *int64, err *error) {
  122. wire.WriteTo([]byte(Fmt(`{"chain_id":%s`, jsonEscape(chainID))), w, n, err)
  123. wire.WriteTo([]byte(Fmt(`,"tx":[%v,{"inputs":[`, TxTypeSend)), w, n, err)
  124. for i, in := range tx.Inputs {
  125. in.WriteSignBytes(w, n, err)
  126. if i != len(tx.Inputs)-1 {
  127. wire.WriteTo([]byte(","), w, n, err)
  128. }
  129. }
  130. wire.WriteTo([]byte(`],"outputs":[`), w, n, err)
  131. for i, out := range tx.Outputs {
  132. out.WriteSignBytes(w, n, err)
  133. if i != len(tx.Outputs)-1 {
  134. wire.WriteTo([]byte(","), w, n, err)
  135. }
  136. }
  137. wire.WriteTo([]byte(`]}]}`), w, n, err)
  138. }
  139. func (tx *SendTx) String() string {
  140. return Fmt("SendTx{%v -> %v}", tx.Inputs, tx.Outputs)
  141. }
  142. //-----------------------------------------------------------------------------
  143. type CallTx struct {
  144. Input *TxInput `json:"input"`
  145. Address []byte `json:"address"`
  146. GasLimit int64 `json:"gas_limit"`
  147. Fee int64 `json:"fee"`
  148. Data []byte `json:"data"`
  149. }
  150. func (tx *CallTx) WriteSignBytes(chainID string, w io.Writer, n *int64, err *error) {
  151. wire.WriteTo([]byte(Fmt(`{"chain_id":%s`, jsonEscape(chainID))), w, n, err)
  152. wire.WriteTo([]byte(Fmt(`,"tx":[%v,{"address":"%X","data":"%X"`, TxTypeCall, tx.Address, tx.Data)), w, n, err)
  153. wire.WriteTo([]byte(Fmt(`,"fee":%v,"gas_limit":%v,"input":`, tx.Fee, tx.GasLimit)), w, n, err)
  154. tx.Input.WriteSignBytes(w, n, err)
  155. wire.WriteTo([]byte(`}]}`), w, n, err)
  156. }
  157. func (tx *CallTx) String() string {
  158. return Fmt("CallTx{%v -> %x: %x}", tx.Input, tx.Address, tx.Data)
  159. }
  160. func NewContractAddress(caller []byte, nonce int) []byte {
  161. temp := make([]byte, 32+8)
  162. copy(temp, caller)
  163. PutInt64BE(temp[32:], int64(nonce))
  164. hasher := ripemd160.New()
  165. hasher.Write(temp) // does not error
  166. return hasher.Sum(nil)
  167. }
  168. //-----------------------------------------------------------------------------
  169. type NameTx struct {
  170. Input *TxInput `json:"input"`
  171. Name string `json:"name"`
  172. Data string `json:"data"`
  173. Fee int64 `json:"fee"`
  174. }
  175. func (tx *NameTx) WriteSignBytes(chainID string, w io.Writer, n *int64, err *error) {
  176. wire.WriteTo([]byte(Fmt(`{"chain_id":%s`, jsonEscape(chainID))), w, n, err)
  177. wire.WriteTo([]byte(Fmt(`,"tx":[%v,{"data":%s,"fee":%v`, TxTypeName, jsonEscape(tx.Data), tx.Fee)), w, n, err)
  178. wire.WriteTo([]byte(`,"input":`), w, n, err)
  179. tx.Input.WriteSignBytes(w, n, err)
  180. wire.WriteTo([]byte(Fmt(`,"name":%s`, jsonEscape(tx.Name))), w, n, err)
  181. wire.WriteTo([]byte(`}]}`), w, n, err)
  182. }
  183. func (tx *NameTx) ValidateStrings() error {
  184. if len(tx.Name) == 0 {
  185. return errors.New("Name must not be empty")
  186. }
  187. if len(tx.Name) > MaxNameLength {
  188. return errors.New(Fmt("Name is too long. Max %d bytes", MaxNameLength))
  189. }
  190. if len(tx.Data) > MaxDataLength {
  191. return errors.New(Fmt("Data is too long. Max %d bytes", MaxDataLength))
  192. }
  193. if !validateNameRegEntryName(tx.Name) {
  194. return errors.New(Fmt("Invalid characters found in NameTx.Name (%s). Only alphanumeric, underscores, and forward slashes allowed", tx.Name))
  195. }
  196. if !validateNameRegEntryData(tx.Data) {
  197. return errors.New(Fmt("Invalid characters found in NameTx.Data (%s). Only the kind of things found in a JSON file are allowed", tx.Data))
  198. }
  199. return nil
  200. }
  201. func (tx *NameTx) BaseEntryCost() int64 {
  202. return BaseEntryCost(tx.Name, tx.Data)
  203. }
  204. func (tx *NameTx) String() string {
  205. return Fmt("NameTx{%v -> %s: %s}", tx.Input, tx.Name, tx.Data)
  206. }
  207. //-----------------------------------------------------------------------------
  208. type BondTx struct {
  209. PubKey acm.PubKeyEd25519 `json:"pub_key"`
  210. Signature acm.SignatureEd25519 `json:"signature"`
  211. Inputs []*TxInput `json:"inputs"`
  212. UnbondTo []*TxOutput `json:"unbond_to"`
  213. }
  214. func (tx *BondTx) WriteSignBytes(chainID string, w io.Writer, n *int64, err *error) {
  215. wire.WriteTo([]byte(Fmt(`{"chain_id":%s`, jsonEscape(chainID))), w, n, err)
  216. wire.WriteTo([]byte(Fmt(`,"tx":[%v,{"inputs":[`, TxTypeBond)), w, n, err)
  217. for i, in := range tx.Inputs {
  218. in.WriteSignBytes(w, n, err)
  219. if i != len(tx.Inputs)-1 {
  220. wire.WriteTo([]byte(","), w, n, err)
  221. }
  222. }
  223. wire.WriteTo([]byte(Fmt(`],"pub_key":`)), w, n, err)
  224. wire.WriteTo(wire.JSONBytes(tx.PubKey), w, n, err)
  225. wire.WriteTo([]byte(`,"unbond_to":[`), w, n, err)
  226. for i, out := range tx.UnbondTo {
  227. out.WriteSignBytes(w, n, err)
  228. if i != len(tx.UnbondTo)-1 {
  229. wire.WriteTo([]byte(","), w, n, err)
  230. }
  231. }
  232. wire.WriteTo([]byte(`]}]}`), w, n, err)
  233. }
  234. func (tx *BondTx) String() string {
  235. return Fmt("BondTx{%v: %v -> %v}", tx.PubKey, tx.Inputs, tx.UnbondTo)
  236. }
  237. //-----------------------------------------------------------------------------
  238. type UnbondTx struct {
  239. Address []byte `json:"address"`
  240. Height int `json:"height"`
  241. Signature acm.SignatureEd25519 `json:"signature"`
  242. }
  243. func (tx *UnbondTx) WriteSignBytes(chainID string, w io.Writer, n *int64, err *error) {
  244. wire.WriteTo([]byte(Fmt(`{"chain_id":%s`, jsonEscape(chainID))), w, n, err)
  245. wire.WriteTo([]byte(Fmt(`,"tx":[%v,{"address":"%X","height":%v}]}`, TxTypeUnbond, tx.Address, tx.Height)), w, n, err)
  246. }
  247. func (tx *UnbondTx) String() string {
  248. return Fmt("UnbondTx{%X,%v,%v}", tx.Address, tx.Height, tx.Signature)
  249. }
  250. //-----------------------------------------------------------------------------
  251. type RebondTx struct {
  252. Address []byte `json:"address"`
  253. Height int `json:"height"`
  254. Signature acm.SignatureEd25519 `json:"signature"`
  255. }
  256. func (tx *RebondTx) WriteSignBytes(chainID string, w io.Writer, n *int64, err *error) {
  257. wire.WriteTo([]byte(Fmt(`{"chain_id":%s`, jsonEscape(chainID))), w, n, err)
  258. wire.WriteTo([]byte(Fmt(`,"tx":[%v,{"address":"%X","height":%v}]}`, TxTypeRebond, tx.Address, tx.Height)), w, n, err)
  259. }
  260. func (tx *RebondTx) String() string {
  261. return Fmt("RebondTx{%X,%v,%v}", tx.Address, tx.Height, tx.Signature)
  262. }
  263. //-----------------------------------------------------------------------------
  264. type DupeoutTx struct {
  265. Address []byte `json:"address"`
  266. VoteA Vote `json:"vote_a"`
  267. VoteB Vote `json:"vote_b"`
  268. }
  269. func (tx *DupeoutTx) WriteSignBytes(chainID string, w io.Writer, n *int64, err *error) {
  270. PanicSanity("DupeoutTx has no sign bytes")
  271. }
  272. func (tx *DupeoutTx) String() string {
  273. return Fmt("DupeoutTx{%X,%v,%v}", tx.Address, tx.VoteA, tx.VoteB)
  274. }
  275. //-----------------------------------------------------------------------------
  276. type PermissionsTx struct {
  277. Input *TxInput `json:"input"`
  278. PermArgs ptypes.PermArgs `json:"args"`
  279. }
  280. func (tx *PermissionsTx) WriteSignBytes(chainID string, w io.Writer, n *int64, err *error) {
  281. wire.WriteTo([]byte(Fmt(`{"chain_id":%s`, jsonEscape(chainID))), w, n, err)
  282. wire.WriteTo([]byte(Fmt(`,"tx":[%v,{"args":"`, TxTypePermissions)), w, n, err)
  283. wire.WriteJSON(tx.PermArgs, w, n, err)
  284. wire.WriteTo([]byte(`","input":`), w, n, err)
  285. tx.Input.WriteSignBytes(w, n, err)
  286. wire.WriteTo([]byte(`}]}`), w, n, err)
  287. }
  288. func (tx *PermissionsTx) String() string {
  289. return Fmt("PermissionsTx{%v -> %v}", tx.Input, tx.PermArgs)
  290. }
  291. //-----------------------------------------------------------------------------
  292. // This should match the leaf hashes of Block.Data.Hash()'s SimpleMerkleTree.
  293. func TxID(chainID string, tx Tx) []byte {
  294. signBytes := acm.SignBytes(chainID, tx)
  295. return wire.BinaryRipemd160(signBytes)
  296. }
  297. //--------------------------------------------------------------------------------
  298. // Contract: This function is deterministic and completely reversible.
  299. func jsonEscape(str string) string {
  300. escapedBytes, err := json.Marshal(str)
  301. if err != nil {
  302. PanicSanity(Fmt("Error json-escaping a string", str))
  303. }
  304. return string(escapedBytes)
  305. }