-
Notifications
You must be signed in to change notification settings - Fork 21
/
newallocation.go
292 lines (254 loc) · 7.95 KB
/
newallocation.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
package cmd
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"math"
"os"
"strconv"
"strings"
"time"
"github.com/0chain/gosdk/zboxcore/blockchain"
"github.com/spf13/pflag"
"github.com/0chain/gosdk/zboxcore/sdk"
"github.com/0chain/gosdk/zcncore"
"github.com/0chain/zboxcli/util"
"github.com/spf13/cobra"
)
var (
datashards, parityshards *int
size *int64
allocationFileName *string
)
func getPriceRange(val string) (pr sdk.PriceRange, err error) {
var ss = strings.Split(val, "-")
if len(ss) != 2 {
err = fmt.Errorf("invalid price range format: %q", val)
return
}
var minf, maxf float64
if minf, err = strconv.ParseFloat(ss[0], 64); err != nil {
return
}
if maxf, err = strconv.ParseFloat(ss[1], 64); err != nil {
return
}
pr.Min = zcncore.ConvertToValue(minf)
pr.Max = zcncore.ConvertToValue(maxf)
return
}
// newallocationCmd represents the new allocation command
var newallocationCmd = &cobra.Command{
Use: "newallocation",
Short: "Creates a new allocation",
Long: `Creates a new allocation`,
Args: cobra.MinimumNArgs(0),
Run: func(cmd *cobra.Command, args []string) {
var flags = cmd.Flags()
costOnly, _ := cmd.Flags().GetBool("cost")
if flags.Changed("free_storage") {
if costOnly {
log.Print("Cost for the given allocation: ", 0)
return
}
lock, freeStorageMarker := processFreeStorageFlags(flags)
if lock < 0 {
log.Fatal("Only positive values are allowed for --lock")
}
allocationID, _, err := sdk.CreateFreeAllocation(freeStorageMarker, lock)
if err != nil {
log.Fatal("Error creating free allocation: ", err)
}
log.Print("Allocation created: ", allocationID)
storeAllocation(allocationID)
return
}
if datashards == nil || parityshards == nil || size == nil {
log.Fatal("Invalid allocation parameters.")
}
var (
lock int64 // lock with given number of tokens
err error //
)
if !costOnly {
if !flags.Changed("lock") {
log.Fatal("missing required 'lock' argument")
}
}
convertFromUSD, _ := cmd.Flags().GetBool("usd")
var lockf float64
if lockf, err = flags.GetFloat64("lock"); err != nil {
log.Fatal("error: invalid 'lock' value:", err)
}
if lock < 0 {
log.Fatal("Only positive values are allowed for --lock")
}
if convertFromUSD {
lockf, err = zcncore.ConvertUSDToToken(lockf)
if err != nil {
log.Fatal("error: failed to convert to USD : ", err)
}
}
lock = zcncore.ConvertToValue(lockf)
var (
readPrice = sdk.PriceRange{Min: 0, Max: math.MaxInt64}
writePrice = sdk.PriceRange{Min: 0, Max: math.MaxInt64}
mcct time.Duration = 1 * time.Hour
)
if flags.Changed("read_price") {
rps, err := flags.GetString("read_price")
if err != nil {
log.Fatal("invalid read_price value: ", err)
}
pr, err := getPriceRange(rps)
if err != nil {
log.Fatal("invalid read_price value: ", err)
}
readPrice = pr
}
if flags.Changed("write_price") {
wps, err := flags.GetString("write_price")
if err != nil {
log.Fatal("invalid write_price value: ", err)
}
pr, err := getPriceRange(wps)
if err != nil {
log.Fatal("invalid write_price value: ", err)
}
writePrice = pr
}
if flags.Changed("mcct") {
if mcct, err = flags.GetDuration("mcct"); err != nil {
log.Fatal("invalid mcct value: ", err)
}
if mcct <= 1*time.Second {
log.Fatal("invalid mcct value < 1s")
}
}
var expire time.Duration
if expire, err = flags.GetDuration("expire"); err != nil {
log.Fatal("invalid 'expire' flag: ", err)
}
var expireAt = time.Now().Add(expire).Unix()
if costOnly {
minCost, err := sdk.GetAllocationMinLock(*datashards, *parityshards, *size, expireAt, readPrice, writePrice, mcct)
if err != nil {
log.Fatal("Error fetching cost: ", err)
}
log.Print("Cost for the given allocation: ", zcncore.ConvertToToken(minCost))
return
}
var owner string
if flags.Changed("owner") {
if owner, err = flags.GetString("owner"); err != nil {
log.Fatal("invalid owner value: ", err)
}
}
var allocationName string
if flags.Changed("name") {
allocationName, err = flags.GetString("name")
if err != nil {
log.Fatal("invalid allocation name: ", err)
}
}
var allocationID string
if len(owner) == 0 {
allocationID, _, err = sdk.CreateAllocation(allocationName, *datashards, *parityshards,
*size, expireAt, readPrice, writePrice, mcct, lock)
if err != nil {
log.Fatal("Error creating allocation: ", err)
}
} else {
var ownerPublicKey string
if flags.Changed("owner") {
if ownerPublicKey, err = flags.GetString("owner_public_key"); err != nil {
log.Fatal("invalid owner public key: ", err)
}
if len(ownerPublicKey) == 0 {
log.Fatal("must provide owner public key, when creating an allocation for another")
}
}
allocationID, _, err = sdk.CreateAllocationForOwner(allocationName, owner, ownerPublicKey, *datashards, *parityshards,
*size, expireAt, readPrice, writePrice, mcct, lock, blockchain.GetPreferredBlobbers())
if err != nil {
log.Fatal("Error creating allocation: ", err)
}
}
log.Print("Allocation created: ", allocationID)
storeAllocation(allocationID)
},
}
func processFreeStorageFlags(flags *pflag.FlagSet) (int64, string) {
if flags.Changed("read_price") {
log.Fatal("free storage, read_price is predefined")
}
if flags.Changed("write_price") {
log.Fatal("free storage, write_price is predefined")
}
if flags.Changed("mcct") {
log.Fatal("free storage, mcct is predefined")
}
filename, err := flags.GetString("free_storage")
if err != nil {
log.Fatal("invalid free)value: ", err)
}
freeStorageMarker, err := ioutil.ReadFile(filename)
if err != nil {
log.Fatal("cannot read in free_storage file", err)
}
var marker struct {
FreeTokens float64 `json:"free_tokens"`
}
err = json.Unmarshal(freeStorageMarker, &marker)
if err != nil {
log.Fatal("unmarshalling marker", err)
}
return zcncore.ConvertToValue(marker.FreeTokens), string(freeStorageMarker)
}
func init() {
rootCmd.AddCommand(newallocationCmd)
datashards = newallocationCmd.PersistentFlags().Int("data", 2, "--data 2")
parityshards = newallocationCmd.PersistentFlags().Int("parity", 2, "--parity 2")
size = newallocationCmd.PersistentFlags().Int64("size", 2147483648, "--size 10000")
allocationFileName = newallocationCmd.PersistentFlags().String("allocationFileName", "allocation.txt", "--allocationFileName allocation.txt")
newallocationCmd.PersistentFlags().
Float64("lock", 0.0,
"lock write pool with given number of tokens, required")
newallocationCmd.PersistentFlags().
String("read_price", "",
"select blobbers by provided read price range, use form 0.5-1.5, default is [0; inf)")
newallocationCmd.PersistentFlags().
String("write_price", "",
"select blobbers by provided write price range, use form 1.5-2.5, default is [0; inf)")
newallocationCmd.PersistentFlags().
Duration("expire", 720*time.Hour, "duration to allocation expiration")
newallocationCmd.PersistentFlags().
Duration("mcct", 1*time.Hour,
"max challenge completion time, optional, default 1h")
newallocationCmd.Flags().
Bool("usd", false,
"pass this option to give token value in USD")
newallocationCmd.Flags().
Bool("cost", false,
"pass this option to only get the min lock demand")
newallocationCmd.Flags().
String("free_storage", "",
"json file containing marker for free storage")
newallocationCmd.Flags().String("owner", "",
"create an allocation with someone else as owner")
newallocationCmd.Flags().String("owner_public_key", "",
"public key of owner, user when creating an allocation for somone else")
newallocationCmd.Flags().String("name", "", "allocation name")
}
func storeAllocation(allocationID string) {
allocFilePath := util.GetConfigDir() + string(os.PathSeparator) + *allocationFileName
file, err := os.Create(allocFilePath)
if err != nil {
PrintError(err.Error())
os.Exit(1)
}
defer file.Close()
//Only one allocation ID per file.
fmt.Fprint(file, allocationID)
}