/
miner.go
407 lines (348 loc) · 13.4 KB
/
miner.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
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
package cmd
import (
"bytes"
"fmt"
"time"
"github.com/docker/go-units"
"github.com/filecoin-project/go-address"
"github.com/filecoin-project/go-state-types/abi"
"github.com/filecoin-project/go-state-types/big"
power6 "github.com/filecoin-project/specs-actors/v6/actors/builtin/power"
cmds "github.com/ipfs/go-ipfs-cmds"
cbor "github.com/ipfs/go-ipld-cbor"
logging "github.com/ipfs/go-log/v2"
"github.com/filecoin-project/venus/app/node"
"github.com/filecoin-project/venus/pkg/constants"
"github.com/filecoin-project/venus/pkg/wallet"
"github.com/filecoin-project/venus/venus-shared/actors"
"github.com/filecoin-project/venus/venus-shared/actors/adt"
"github.com/filecoin-project/venus/venus-shared/actors/builtin/miner"
"github.com/filecoin-project/venus/venus-shared/actors/builtin/power"
blockstoreutil "github.com/filecoin-project/venus/venus-shared/blockstore"
"github.com/filecoin-project/venus/venus-shared/types"
"github.com/filecoin-project/venus/venus-shared/types/params"
)
var minerCmdLog = logging.Logger("miner.cmd")
var minerCmd = &cmds.Command{
Helptext: cmds.HelpText{
Tagline: "Interact with actors. Actors are built-in smart contracts.",
},
Subcommands: map[string]*cmds.Command{
"new": newMinerCmd,
"info": minerInfoCmd,
"actor": minerActorCmd,
"proving": minerProvingCmd,
},
}
var newMinerCmd = &cmds.Command{
Helptext: cmds.HelpText{
Tagline: "Create a new miner.",
},
Arguments: []cmds.Argument{
cmds.StringArg("owner", true, false, "owner key to use"),
},
Options: []cmds.Option{
cmds.StringOption("worker", "worker key to use (overrides --create-worker-key)"),
cmds.BoolOption("create-worker-key", "Create separate worker key"),
cmds.StringOption("from", "Select which address to send actor creation message from"),
cmds.StringOption("gas-premium", "Set gas premium for initialization messages in AttoFIL").WithDefault("0"),
cmds.StringOption("sector-size", "specify sector size to use"),
},
Run: func(req *cmds.Request, re cmds.ResponseEmitter, env cmds.Environment) error {
ctx := req.Context
owner, err := address.NewFromString(req.Arguments[0])
if err != nil {
return err
}
ssize, err := abi.RegisteredSealProof_StackedDrg32GiBV1.SectorSize()
if err != nil {
return fmt.Errorf("failed to calculate default sector size: %w", err)
}
sectorSize, ok := req.Options["sector-size"].(string)
if ok {
sectorSizeInt, err := units.RAMInBytes(sectorSize)
if err != nil {
return err
}
ssize = abi.SectorSize(sectorSizeInt)
}
gp, _ := req.Options["gas-premium"].(string)
gasPrice, err := types.ParseFIL(gp)
if err != nil {
return fmt.Errorf("failed to parse gas-price flag: %s", err)
}
worker := owner
workerAddr, _ := req.Options["worker-address"].(string)
createWorkerKey, _ := req.Options["create-worker-key"].(bool)
if workerAddr != "" {
worker, err = address.NewFromString(workerAddr)
} else if createWorkerKey { // TODO: Do we need to force this if owner is Secpk?
if !env.(*node.Env).WalletAPI.HasPassword(ctx) {
return errMissPassword
}
if env.(*node.Env).WalletAPI.WalletState(req.Context) == wallet.Lock {
return errWalletLocked
}
if worker, err = env.(*node.Env).WalletAPI.WalletNewAddress(req.Context, address.BLS); err != nil {
return err
}
}
if err != nil {
return err
}
// make sure the worker account exists on chain
_, err = env.(*node.Env).ChainAPI.StateLookupID(ctx, worker, types.EmptyTSK)
if err != nil {
signed, err := env.(*node.Env).MessagePoolAPI.MpoolPushMessage(ctx, &types.Message{
From: owner,
To: worker,
Value: big.NewInt(0),
}, nil)
if err != nil {
return fmt.Errorf("push worker init: %v", err)
}
cid := signed.Cid()
minerCmdLog.Infof("Initializing worker account %s, message: %s", worker, cid)
minerCmdLog.Infof("Waiting for confirmation")
_ = re.Emit("Initializing worker account " + worker.String() + ", message: " + cid.String())
mw, err := env.(*node.Env).ChainAPI.StateWaitMsg(ctx, cid, constants.MessageConfidence, constants.LookbackNoLimit, true)
if err != nil {
return fmt.Errorf("waiting for worker init: %v", err)
}
if mw.Receipt.ExitCode != 0 {
return fmt.Errorf("initializing worker account failed: exit code %d", mw.Receipt.ExitCode)
}
}
nv, err := env.(*node.Env).ChainAPI.StateNetworkVersion(ctx, types.EmptyTSK)
if err != nil {
return fmt.Errorf("getting network version: %v", err)
}
spt, err := miner.WindowPoStProofTypeFromSectorSize(ssize, nv)
if err != nil {
return fmt.Errorf("getting post proof type: %v", err)
}
peerID, err := env.(*node.Env).NetworkAPI.ID(ctx)
if err != nil {
return err
}
params, err := actors.SerializeParams(&power6.CreateMinerParams{
Owner: owner,
Worker: worker,
WindowPoStProofType: spt,
Peer: abi.PeerID(peerID),
})
if err != nil {
return err
}
minerCmdLog.Info("peer id: ", peerID.Pretty())
sender := owner
fromstr, _ := req.Options["from"].(string)
if len(fromstr) != 0 {
faddr, err := address.NewFromString(fromstr)
if err != nil {
return fmt.Errorf("could not parse from address: %v", err)
}
sender = faddr
}
createStorageMinerMsg := &types.Message{
To: power.Address,
From: sender,
Value: big.Zero(),
Method: power.Methods.CreateMiner,
Params: params,
GasLimit: 0,
GasPremium: abi.TokenAmount{Int: gasPrice.Int},
}
signed, err := env.(*node.Env).MessagePoolAPI.MpoolPushMessage(ctx, createStorageMinerMsg, nil)
if err != nil {
return fmt.Errorf("pushing createMiner message: %w", err)
}
cid := signed.Cid()
minerCmdLog.Infof("Pushed CreateMiner message: %s", cid)
minerCmdLog.Infof("Waiting for confirmation")
_ = re.Emit("Pushed CreateMiner message: " + cid.String())
mw, err := env.(*node.Env).ChainAPI.StateWaitMsg(ctx, cid, constants.MessageConfidence, constants.LookbackNoLimit, true)
if err != nil {
return fmt.Errorf("waiting for createMiner message: %v", err)
}
if mw.Receipt.ExitCode != 0 {
return fmt.Errorf("create miner failed: exit code %d", mw.Receipt.ExitCode)
}
var retval power6.CreateMinerReturn
if err := retval.UnmarshalCBOR(bytes.NewReader(mw.Receipt.Return)); err != nil {
return err
}
s := fmt.Sprintf("New miners address is: %s (%s)", retval.IDAddress, retval.RobustAddress)
minerCmdLog.Info(s)
return re.Emit(s)
},
Type: "",
}
var minerInfoCmd = &cmds.Command{
Helptext: cmds.HelpText{
Tagline: "Print miner info.",
},
Options: []cmds.Option{
cmds.BoolOption("hide-sectors-info", "hide-sectors-info"),
},
Arguments: []cmds.Argument{
cmds.StringArg("address", true, false, "Address of miner to show"),
},
Run: func(req *cmds.Request, re cmds.ResponseEmitter, env cmds.Environment) error {
maddr, err := address.NewFromString(req.Arguments[0])
if err != nil {
return err
}
ctx := req.Context
blockstoreAPI := env.(*node.Env).BlockStoreAPI
api := env.(*node.Env).ChainAPI
blockDelay, err := getBlockDelay(ctx, env)
if err != nil {
return err
}
head, err := api.ChainHead(ctx)
if err != nil {
return err
}
buf := new(bytes.Buffer)
writer := NewSilentWriter(buf)
var chainSyncStr string
switch {
case time.Now().Unix()-int64(head.MinTimestamp()) < int64(blockDelay*3/2): // within 1.5 epochs
chainSyncStr = "[Chain: sync ok]"
case time.Now().Unix()-int64(head.MinTimestamp()) < int64(blockDelay*5): // within 5 epochs
chainSyncStr = fmt.Sprintf("[Chain: sync slow (%s behind)]", time.Since(time.Unix(int64(head.MinTimestamp()), 0)).Truncate(time.Second))
default:
chainSyncStr = fmt.Sprintf("[Chain: sync behind! (%s behind)]", time.Since(time.Unix(int64(head.MinTimestamp()), 0)).Truncate(time.Second))
}
basefee := head.MinTicketBlock().ParentBaseFee
writer.Printf("%s [basefee %s]\n", chainSyncStr, types.FIL(basefee).Short())
mact, err := api.StateGetActor(ctx, maddr, types.EmptyTSK)
if err != nil {
return err
}
tbs := blockstoreutil.NewTieredBstore(blockstoreutil.NewAPIBlockstore(blockstoreAPI), blockstoreutil.NewTemporary())
mas, err := miner.Load(adt.WrapStore(ctx, cbor.NewCborStore(tbs)), mact)
if err != nil {
return err
}
// Sector size
mi, err := api.StateMinerInfo(ctx, maddr, types.EmptyTSK)
if err != nil {
return err
}
ssize := types.SizeStr(big.NewInt(int64(mi.SectorSize)))
writer.Printf("Miner: %s (%s sectors)\n", maddr, ssize)
pow, err := api.StateMinerPower(ctx, maddr, types.EmptyTSK)
if err != nil {
return err
}
rpercI := big.Div(big.Mul(pow.MinerPower.RawBytePower, big.NewInt(1000000)), pow.TotalPower.RawBytePower)
qpercI := big.Div(big.Mul(pow.MinerPower.QualityAdjPower, big.NewInt(1000000)), pow.TotalPower.QualityAdjPower)
writer.Printf("Power: %s / %s (%0.4f%%)\n",
types.DeciStr(pow.MinerPower.QualityAdjPower),
types.DeciStr(pow.TotalPower.QualityAdjPower),
float64(qpercI.Int64())/10000)
writer.Printf("Raw: %s / %s (%0.4f%%)\n",
types.SizeStr(pow.MinerPower.RawBytePower),
types.SizeStr(pow.TotalPower.RawBytePower),
float64(rpercI.Int64())/10000)
secCounts, err := api.StateMinerSectorCount(ctx, maddr, types.EmptyTSK)
if err != nil {
return err
}
proving := secCounts.Active + secCounts.Faulty
nfaults := secCounts.Faulty
writer.Printf("\tCommitted: %s\n", types.SizeStr(big.Mul(big.NewInt(int64(secCounts.Live)), big.NewInt(int64(mi.SectorSize)))))
if nfaults == 0 {
writer.Printf("\tProving: %s\n", types.SizeStr(big.Mul(big.NewInt(int64(proving)), big.NewInt(int64(mi.SectorSize)))))
} else {
var faultyPercentage float64
if secCounts.Live != 0 {
faultyPercentage = float64(10000*nfaults/secCounts.Live) / 100.
}
writer.Printf("Proving: %s (%s Faulty, %.2f%%)\n",
types.SizeStr(big.Mul(big.NewInt(int64(proving)), big.NewInt(int64(mi.SectorSize)))),
types.SizeStr(big.Mul(big.NewInt(int64(nfaults)), big.NewInt(int64(mi.SectorSize)))),
faultyPercentage)
}
if !pow.HasMinPower {
writer.Println("Below minimum power threshold, no blocks will be won")
} else {
expWinChance := float64(big.Mul(qpercI, big.NewInt(int64(params.BlocksPerEpoch))).Int64()) / 1000000
if expWinChance > 0 {
if expWinChance > 1 {
expWinChance = 1
}
winRate := time.Duration(float64(time.Second*time.Duration(blockDelay)) / expWinChance)
winPerDay := float64(time.Hour*24) / float64(winRate)
writer.Printf("Expected block win rate: %.4f/day (every %s)\n", winPerDay, winRate.Truncate(time.Second))
}
}
writer.Println()
spendable := big.Zero()
// NOTE: there's no need to unlock anything here. Funds only
// vest on deadline boundaries, and they're unlocked by cron.
lockedFunds, err := mas.LockedFunds()
if err != nil {
return fmt.Errorf("getting locked funds: %w", err)
}
availBalance, err := mas.AvailableBalance(mact.Balance)
if err != nil {
return fmt.Errorf("getting available balance: %w", err)
}
spendable = big.Add(spendable, availBalance)
writer.Printf("Miner Balance: %s\n", types.FIL(mact.Balance).Short())
writer.Printf(" PreCommit: %s\n", types.FIL(lockedFunds.PreCommitDeposits).Short())
writer.Printf(" Pledge: %s\n", types.FIL(lockedFunds.InitialPledgeRequirement).Short())
writer.Printf(" Vesting: %s\n", types.FIL(lockedFunds.VestingFunds).Short())
writer.Printf(" Available: %s\n", types.FIL(availBalance).Short())
mb, err := api.StateMarketBalance(ctx, maddr, types.EmptyTSK)
if err != nil {
return fmt.Errorf("getting market balance: %w", err)
}
spendable = big.Add(spendable, big.Sub(mb.Escrow, mb.Locked))
writer.Printf("Market Balance: %s\n", types.FIL(mb.Escrow).Short())
writer.Printf(" Locked: %s\n", types.FIL(mb.Locked).Short())
writer.Printf(" Available: %s\n", types.FIL(big.Sub(mb.Escrow, mb.Locked)).Short())
wb, err := env.(*node.Env).WalletAPI.WalletBalance(ctx, mi.Worker)
if err != nil {
return fmt.Errorf("getting worker balance: %w", err)
}
spendable = big.Add(spendable, wb)
writer.Printf("Worker Balance: %s\n", types.FIL(wb).Short())
if len(mi.ControlAddresses) > 0 {
cbsum := big.Zero()
for _, ca := range mi.ControlAddresses {
b, err := env.(*node.Env).WalletAPI.WalletBalance(ctx, ca)
if err != nil {
return fmt.Errorf("getting control address balance: %w", err)
}
cbsum = big.Add(cbsum, b)
}
spendable = big.Add(spendable, cbsum)
writer.Printf(" Control: %s\n", types.FIL(cbsum).Short())
}
writer.Printf("Total Spendable: %s\n", types.FIL(spendable).Short())
if mi.Beneficiary != address.Undef {
writer.Printf("Beneficiary:\t%s\n", mi.Beneficiary)
if mi.Beneficiary != mi.Owner {
writer.Printf("Beneficiary Quota:\t%s\n", mi.BeneficiaryTerm.Quota)
writer.Printf("Beneficiary Used Quota:\t%s\n", mi.BeneficiaryTerm.UsedQuota)
writer.Printf("Beneficiary Expiration:\t%s\n", mi.BeneficiaryTerm.Expiration)
}
}
if mi.PendingBeneficiaryTerm != nil {
writer.Printf("Pending Beneficiary Term:\n")
writer.Printf("New Beneficiary:\t%s\n", mi.PendingBeneficiaryTerm.NewBeneficiary)
writer.Printf("New Quota:\t%s\n", mi.PendingBeneficiaryTerm.NewQuota)
writer.Printf("New Expiration:\t%s\n", mi.PendingBeneficiaryTerm.NewExpiration)
writer.Printf("Approved By Beneficiary:\t%t\n", mi.PendingBeneficiaryTerm.ApprovedByBeneficiary)
writer.Printf("Approved By Nominee:\t%t\n", mi.PendingBeneficiaryTerm.ApprovedByNominee)
}
// TODO: grab actr state / info
// * Sealed sectors (count / bytes)
// * Power
return re.Emit(buf)
},
}