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.

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