This repository was archived by the owner on Oct 11, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 34
/
Copy pathcontract.go
356 lines (321 loc) · 9.84 KB
/
contract.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
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
package killcord
import (
"context"
"encoding/hex"
"errors"
"fmt"
"io/ioutil"
"log"
"math/big"
"os"
"path/filepath"
"strings"
"time"
"github.com/ethereum/go-ethereum/accounts/abi/bind"
"github.com/ethereum/go-ethereum/accounts/keystore"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/ethclient"
"github.com/nomasters/killcord/contract"
)
const (
defaultETHRPCPDev = "https://ropsten.infura.io/v3/31eba034ccd74fc8ab6ac9ba0e24da2f"
defaultETHRPCDProd = "https://mainnet.infura.io/v3/31eba034ccd74fc8ab6ac9ba0e24da2f"
)
var (
contractDir string
fullKeyStorePath string
relativeKeyStorePath string
ethereumRPCPath string = defaultETHRPCPDev
)
func init() {
contractDir = filepath.Join(ProjectPath, "contract")
fullKeyStorePath = filepath.Join(contractDir, "data", "keystore")
relativeKeyStorePath = filepath.Join("contract", "data", "keystore")
}
// A simple func to convert wei to ETH
func weiToETH(i *big.Int) float64 {
f := float64(i.Int64())
return f / 1000000000000000000
}
// Gracefully resolve Ethereum RPC path by waterfalling through
// Options > Project > Defaults
func (s *Session) setEthereumRPCPath() {
if s.Options.Contract.RPCURL != "" {
ethereumRPCPath = s.Options.Contract.RPCURL
return
}
if s.Config.Contract.RPCURL != "" {
ethereumRPCPath = s.Config.Contract.RPCURL
return
}
if s.Config.Contract.Mode == "mainnet" {
ethereumRPCPath = defaultETHRPCDProd
return
}
s.Config.Contract.Mode = "testnet"
ethereumRPCPath = defaultETHRPCPDev
}
// ConfigEthereum configures the ethereum accounts used by killcord and adds
// the settings to the primary config. This includes account
// generation, password creation, and keystore creation.
func (s *Session) ConfigEthereum() error {
ks := newKeyStore()
if err := s.Config.Contract.Owner.New(ks); err != nil {
return err
}
if err := s.Config.Contract.Publisher.New(ks); err != nil {
return err
}
fmt.Println("ethereum: initializing")
s.Config.Contract.Provider = "ethereum"
s.Config.Contract.Status = "initialized"
fmt.Println("ethereum: configured")
fmt.Printf(`
Congrats! You've successfully initialized your ethereum owner and publisher accounts.
Next, you'll need to add a little bit of ETH to both accounts to move forward.
You should add a minimum of:
- 0.03 ETH to your owner account
- 0.01 ETH to your publisher account
your owner account address is: 0x%v
your publisher account address is: 0x%v
You can check your ethereum account balances with the "killcord status" command.
If this is your first time using Ethereum, metamask (https://metamask.io/) is the
easiest way to get started.
`, s.Config.Contract.Owner.Address, s.Config.Contract.Publisher.Address)
return nil
}
func newKeyStore() *keystore.KeyStore {
return keystore.NewKeyStore(fullKeyStorePath, keystore.StandardScryptN, keystore.StandardScryptP)
}
// New makes a account
func (a *AccountConfig) New(ks *keystore.KeyStore) error {
pw := generateKey()
newAcc, err := ks.NewAccount(pw)
if err != nil {
return err
}
a.Address = hex.EncodeToString(newAcc.Address[:])
a.Password = pw
a.KeyStore, err = getKeyStore(a)
if err != nil {
return err
}
os.RemoveAll(contractDir)
return nil
}
func newContractAuthSession(account AccountConfig, contractID string) (*contract.KillCordSession, error) {
conn, err := ethclient.Dial(ethereumRPCPath)
if err != nil {
return &contract.KillCordSession{}, fmt.Errorf("Failed to connect to the Ethereum client: %v", err)
}
auth, err := bind.NewTransactor(strings.NewReader(account.KeyStore), account.Password)
if err != nil {
return &contract.KillCordSession{}, fmt.Errorf("Failed to create authorized transactor: %v", err)
}
killcord, err := contract.NewKillCord(common.HexToAddress("0x"+contractID), conn)
if err != nil {
return &contract.KillCordSession{}, fmt.Errorf("Failed to instantiate a killcord contract: %v", err)
}
return &contract.KillCordSession{
Contract: killcord,
CallOpts: bind.CallOpts{
Pending: true,
},
TransactOpts: bind.TransactOpts{
From: auth.From,
Signer: auth.Signer,
},
}, nil
}
func newContractCallerSession(contractID string) (*contract.KillCordSession, error) {
conn, err := ethclient.Dial(ethereumRPCPath)
if err != nil {
return &contract.KillCordSession{}, fmt.Errorf("Failed to connect to the Ethereum client: %v", err)
}
killcord, err := contract.NewKillCord(common.HexToAddress("0x"+contractID), conn)
if err != nil {
return &contract.KillCordSession{}, fmt.Errorf("Failed to instantiate a killcord contract: %v", err)
}
return &contract.KillCordSession{
Contract: killcord,
CallOpts: bind.CallOpts{
Pending: true,
},
}, nil
}
// GetLastCheckIn returns a timestamp or error from last checkin
func GetLastCheckIn(contractID string) (time.Time, error) {
session, err := newContractCallerSession(contractID)
if err != nil {
return time.Now(), err
}
timeStamp, err := session.GetLastCheckIn()
if err != nil {
return time.Now(), fmt.Errorf("Failed to get last checkin: %v", err)
}
return time.Unix(timeStamp.Int64(), 0), nil
}
func GetKey(contractID string) (string, error) {
session, err := newContractCallerSession(contractID)
if err != nil {
return "", err
}
key, err := session.GetKey()
if err != nil {
return "", fmt.Errorf("Failed to get last checkin: %v", err)
}
return key, nil
}
func GetOwner(contractID string) (string, error) {
session, err := newContractCallerSession(contractID)
if err != nil {
return "", err
}
address, err := session.GetOwner()
if err != nil {
return "", fmt.Errorf("Failed to get last checkin: %v", err)
}
return address.String(), nil
}
func GetPublisher(contractID string) (string, error) {
session, err := newContractCallerSession(contractID)
if err != nil {
return "", err
}
address, err := session.GetPublisher()
if err != nil {
return "", fmt.Errorf("Failed to get last checkin: %v", err)
}
return address.String(), nil
}
func GetPayloadEndpoint(contractID string) (string, error) {
session, err := newContractCallerSession(contractID)
if err != nil {
return "", err
}
endpoint, err := session.GetPayloadEndpoint()
if err != nil {
return "", fmt.Errorf("Failed to get last checkin: %v", err)
}
return endpoint, nil
}
// Runs a simple checkin to the contract with the owner account.
// TODO: support options for confirming checkin, not just submitting it
func CheckIn(account AccountConfig, contractID string) error {
session, err := newContractAuthSession(account, contractID)
if err != nil {
return err
}
if _, err = session.CheckIn(); err != nil {
return fmt.Errorf("Failed to set Endpoint: %v", err)
}
fmt.Println("checkin successfully submitted")
return nil
}
func (s *Session) CheckIn() error {
if err := CheckIn(s.Config.Contract.Owner, s.Config.Contract.ID); err != nil {
return err
}
return nil
}
func SetKey(account AccountConfig, contractID string, secret string) error {
session, err := newContractAuthSession(account, contractID)
if err != nil {
return err
}
if _, err := session.SetKey(secret); err != nil {
return fmt.Errorf("Failed to set Publishable Key: %v", err)
}
fmt.Printf("key publication submitted with %v\n", account.Address)
return nil
}
func KillContract(account AccountConfig, contractID string) error {
session, err := newContractAuthSession(account, contractID)
if err != nil {
return err
}
if _, err := session.Kill(); err != nil {
return fmt.Errorf("Failed to set Endpoint: %v", err)
}
fmt.Println("contract kill submitted")
return nil
}
func (s *Session) KillContract() error {
if err := KillContract(s.Config.Contract.Owner, s.Config.Contract.ID); err != nil {
return err
}
return nil
}
func SetPayloadEndpoint(account AccountConfig, contractID string, payloadID string) error {
session, err := newContractAuthSession(account, contractID)
if err != nil {
return err
}
if _, err := session.SetPayloadEndpoint(payloadID); err != nil {
return fmt.Errorf("Failed to set Endpoint: %v", err)
}
fmt.Println("payload endpoint successfully submitted to contract")
return nil
}
func (s *Session) DeployContract() error {
if s.Config.Contract.ID != "" {
return fmt.Errorf("contract 0x%v already deployed, skipping", s.Config.Contract.ID)
}
conn, err := ethclient.Dial(ethereumRPCPath)
if err != nil {
log.Fatalf("Failed to connect to the Ethereum client: %v", err)
return err
}
auth, err := bind.NewTransactor(strings.NewReader(s.Config.Contract.Owner.KeyStore), s.Config.Contract.Owner.Password)
if err != nil {
log.Fatalf("Failed to create authorized transactor: %v", err)
return err
}
// TODO: this was set arbitrarily, should dive into this more
// auth.GasLimit = big.NewInt(50000)
// auth.GasPrice = big.NewInt(10)
publisher := common.HexToAddress("0x" + s.Config.Contract.Publisher.Address)
address, tx, _, err := contract.DeployKillCord(auth, conn, publisher)
if err != nil {
log.Fatalf("Failed to deploy new killcord contract: %v", err)
return err
}
fmt.Printf("Contract pending deploy: 0x%x\n", address)
fmt.Printf("Transaction waiting to be mined: 0x%x\n\n", tx.Hash())
s.Config.Contract.ID = hex.EncodeToString(address[:])
return nil
}
func getBalance(account string) float64 {
conn, err := ethclient.Dial(ethereumRPCPath)
if err != nil {
log.Fatalf("Failed to connect to the Ethereum client: %v", err)
}
a := common.HexToAddress("0x" + account)
balance, err := conn.BalanceAt(context.TODO(), a, nil)
if err != nil {
log.Fatalf("balance check failed %v\n", err)
}
b := balance
return weiToETH(b)
}
func getKeyStore(account *AccountConfig) (string, error) {
var file string
files, err := filepath.Glob(relativeKeyStorePath + "/*")
if err != nil {
return "", err
}
for _, f := range files {
if strings.Contains(f, account.Address) {
file = f
break
}
}
if file == "" {
return "", errors.New("No Contract Account Found")
}
content, err := ioutil.ReadFile(file)
if err != nil {
return "", err
}
return string(content), nil
}