-
Notifications
You must be signed in to change notification settings - Fork 29
/
entity.go
250 lines (225 loc) · 7.92 KB
/
entity.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
package transaction
import (
"encoding/json"
"fmt"
"sync"
"github.com/0chain/gosdk/core/common"
"github.com/0chain/gosdk/core/encryption"
"github.com/0chain/gosdk/core/util"
)
const TXN_SUBMIT_URL = "v1/transaction/put"
const TXN_VERIFY_URL = "v1/transaction/get/confirmation?hash="
var ErrNoTxnDetail = common.NewError("missing_transaction_detail", "No transaction detail was found on any of the sharders")
//Transaction entity that encapsulates the transaction related data and meta data
type Transaction struct {
Hash string `json:"hash,omitempty"`
Version string `json:"version,omitempty"`
ClientID string `json:"client_id,omitempty"`
PublicKey string `json:"public_key,omitempty"`
ToClientID string `json:"to_client_id,omitempty"`
ChainID string `json:"chain_id,omitempty"`
TransactionData string `json:"transaction_data"`
Value int64 `json:"transaction_value"`
Signature string `json:"signature,omitempty"`
CreationDate int64 `json:"creation_date,omitempty"`
TransactionType int `json:"transaction_type"`
TransactionOutput string `json:"transaction_output,omitempty"`
TransactionFee int64 `json:"transaction_fee"`
OutputHash string `json:"txn_output_hash"`
}
//TxnReceipt - a transaction receipt is a processed transaction that contains the output
type TxnReceipt struct {
Transaction *Transaction
}
type SmartContractTxnData struct {
Name string `json:"name"`
InputArgs interface{} `json:"input"`
}
type StorageAllocation struct {
ID string `json:"id"`
DataShards int `json:"data_shards"`
ParityShards int `json:"parity_shards"`
Size int64 `json:"size"`
Expiration int64 `json:"expiration_date"`
Owner string `json:"owner_id"`
OwnerPublicKey string `json:"owner_public_key"`
ReadRatio *Ratio `json:"read_ratio"`
WriteRatio *Ratio `json:"write_ratio"`
}
type Ratio struct {
ZCN int64 `json:"zcn"`
Size int64 `json:"size"`
}
type RoundBlockHeader struct {
Version string `json:"version"`
CreationData int64 `json:"creation_date"`
Hash string `json:"hash"`
MinerID string `json:"miner_id"`
Round int64 `json:"round"`
RoundRandomSeed int64 `json:"round_random_seed"`
MerkleTreeRoot string `json:"merkle_tree_root"`
StateHash string `json:"state_hash"`
ReceiptMerkleTreeRoot string `json:"receipt_merkle_tree_root"`
NumberOfTxns int64 `json:"num_txns"`
}
const (
NEW_ALLOCATION_REQUEST = "new_allocation_request"
UPDATE_ALLOCATION_REQUEST = "update_allocation_request"
LOCK_TOKEN = "lock"
UNLOCK_TOKEN = "unlock"
// Vesting SC
VESTING_TRIGGER = "trigger"
VESTING_STOP = "stop"
VESTING_UNLOCK = "unlock"
VESTING_ADD = "add"
VESTING_DELETE = "delete"
VESTING_UPDATE_CONFIG = "update_config"
// Storage SC
STORAGESC_FINALIZE_ALLOCATION = "finalize_allocation"
STORAGESC_CANCEL_ALLOCATION = "cancel_allocation"
STORAGESC_CREATE_ALLOCATION = "new_allocation_request"
STORAGESC_CREATE_READ_POOL = "new_read_pool"
STORAGESC_READ_POOL_LOCK = "read_pool_lock"
STORAGESC_READ_POOL_UNLOCK = "read_pool_unlock"
STORAGESC_STAKE_POOL_LOCK = "stake_pool_lock"
STORAGESC_STAKE_POOL_UNLOCK = "stake_pool_unlock"
STORAGESC_STAKE_POOL_PAY_INTERESTS = "stake_pool_pay_interests"
STORAGESC_UPDATE_BLOBBER_SETTINGS = "update_blobber_settings"
STORAGESC_UPDATE_ALLOCATION = "update_allocation_request"
STORAGESC_WRITE_POOL_LOCK = "write_pool_lock"
STORAGESC_WRITE_POOL_UNLOCK = "write_pool_unlock"
// Miner SC
MINERSC_LOCK = "addToDelegatePool"
MINERSC_UNLOCK = "deleteFromDelegatePool"
MINERSC_SETTINGS = "update_settings"
)
type SignFunc = func(msg string) (string, error)
type VerifyFunc = func(signature, msgHash, publicKey string) (bool, error)
type SignWithWallet = func(msg string, wallet interface{}) (string, error)
func NewTransactionEntity(clientID string, chainID string, publicKey string) *Transaction {
txn := &Transaction{}
txn.Version = "1.0"
txn.ClientID = clientID
txn.CreationDate = int64(common.Now())
txn.ChainID = chainID
txn.PublicKey = publicKey
return txn
}
func (t *Transaction) ComputeHashAndSignWithWallet(signHandler SignWithWallet, signingWallet interface{}) error {
t.ComputeHashData()
var err error
t.Signature, err = signHandler(t.Hash, signingWallet)
if err != nil {
return err
}
return nil
}
func (t *Transaction) ComputeHashAndSign(signHandler SignFunc) error {
t.ComputeHashData()
var err error
t.Signature, err = signHandler(t.Hash)
if err != nil {
return err
}
return nil
}
func (t *Transaction) ComputeHashData() {
hashdata := fmt.Sprintf("%v:%v:%v:%v:%v", t.CreationDate, t.ClientID,
t.ToClientID, t.Value, encryption.Hash(t.TransactionData))
t.Hash = encryption.Hash(hashdata)
}
//GetHash - implement interface
func (rh *TxnReceipt) GetHash() string {
return rh.Transaction.OutputHash
}
/*GetHashBytes - implement Hashable interface */
func (rh *TxnReceipt) GetHashBytes() []byte {
return util.HashStringToBytes(rh.Transaction.OutputHash)
}
//NewTransactionReceipt - create a new transaction receipt
func NewTransactionReceipt(t *Transaction) *TxnReceipt {
return &TxnReceipt{Transaction: t}
}
func (t *Transaction) VerifyTransaction(verifyHandler VerifyFunc) (bool, error) {
// Store the hash
hash := t.Hash
t.ComputeHashData()
if t.Hash != hash {
return false, fmt.Errorf(`{"error":"hash_mismatch", "expected":"%v", "actual":%v"}`, t.Hash, hash)
}
return verifyHandler(t.Signature, t.Hash, t.PublicKey)
}
func SendTransactionSync(txn *Transaction, miners []string) {
wg := sync.WaitGroup{}
wg.Add(len(miners))
for _, miner := range miners {
url := fmt.Sprintf("%v/%v", miner, TXN_SUBMIT_URL)
go sendTransactionToURL(url, txn, &wg)
}
wg.Wait()
}
func sendTransactionToURL(url string, txn *Transaction, wg *sync.WaitGroup) ([]byte, error) {
if wg != nil {
defer wg.Done()
}
postReq, err := util.NewHTTPPostRequest(url, txn)
if err != nil {
//Logger.Error("Error in serializing the transaction", txn, err.Error())
return nil, err
}
postResponse, err := postReq.Post()
if postResponse.StatusCode >= 200 && postResponse.StatusCode <= 299 {
return []byte(postResponse.Body), nil
}
return nil, common.NewError("transaction_send_error", postResponse.Body)
}
func VerifyTransaction(txnHash string, sharders []string) (*Transaction, error) {
numSharders := len(sharders)
numSuccess := 0
var retTxn *Transaction
for _, sharder := range sharders {
url := fmt.Sprintf("%v/%v%v", sharder, TXN_VERIFY_URL, txnHash)
req, err := util.NewHTTPGetRequest(url)
response, err := req.Get()
if err != nil {
//Logger.Error("Error getting transaction confirmation", err.Error())
numSharders--
} else {
if response.StatusCode != 200 {
continue
}
contents := response.Body
var objmap map[string]json.RawMessage
err = json.Unmarshal([]byte(contents), &objmap)
if err != nil {
//Logger.Error("Error unmarshalling response", err.Error())
continue
}
if _, ok := objmap["txn"]; !ok {
//Logger.Info("Not transaction information. Only block summary.", url, contents)
if _, ok := objmap["block_hash"]; ok {
numSuccess++
continue
}
//Logger.Info("Sharder does not have the block summary", url, contents)
continue
}
txn := &Transaction{}
err = json.Unmarshal(objmap["txn"], txn)
if err != nil {
//Logger.Error("Error unmarshalling to get transaction response", err.Error())
}
if len(txn.Signature) > 0 {
retTxn = txn
}
numSuccess++
}
}
if numSharders == 0 || float64(numSuccess*1.0/numSharders) > float64(0.5) {
if retTxn != nil {
return retTxn, nil
}
return nil, ErrNoTxnDetail
}
return nil, common.NewError("transaction_not_found", "Transaction was not found on any of the sharders")
}