GitLab's annual major release is around the corner. Along with a lot of new and exciting features, there will be a few breaking changes. Learn more here.

script.go 12.8 KB
Newer Older
ttt's avatar
script  
ttt committed
1 2 3 4 5 6 7 8 9 10 11 12 13
package main

import (
	"bufio"
	"bytes"
	"flag"
	"fmt"
	"io/ioutil"
	"log"
	"os"
	"os/exec"
	"strconv"
	"strings"
14
	"time"
ttt's avatar
script  
ttt committed
15 16 17
	"unicode"
)

ttt's avatar
ttt committed
18 19
var debug = flag.Bool("debug", false, "print debug information")
var verbose = flag.Bool("v", false, "print out more information")
ttt's avatar
script  
ttt committed
20

ttt's avatar
ttt committed
21 22
const redirectorType = "(contract (pair signature (pair string int)) unit)"

ttt's avatar
script  
ttt committed
23 24 25
func main() {
	flag.Parse()

ttt's avatar
ttt committed
26
	// check for tezos-client
ttt's avatar
ttt committed
27
	if *verbose {
ttt's avatar
ttt committed
28
		fmt.Println("Checking for tezos-client.")
ttt's avatar
ttt committed
29 30
	}

ttt's avatar
ttt committed
31 32
	if _, err := os.Stat("tezos-client"); os.IsNotExist(err) {
		fmt.Println("Please navigate to the folder with your tezos-client and run the script there.")
ttt's avatar
script  
ttt committed
33 34 35
		return
	}

ttt's avatar
ttt committed
36
	// check for file with suffix from previous run
ttt's avatar
ttt committed
37 38 39 40
	if *verbose {
		fmt.Println("Detecting previous runs.")
	}

ttt's avatar
script  
ttt committed
41
	if _, err := os.Stat(".setup_automated_insurance_suffix"); os.IsNotExist(err) {
ttt's avatar
ttt committed
42
		// try detecting suffix
ttt's avatar
ttt committed
43 44 45
		if *verbose {
			fmt.Println("No information found, trying to detect existing identities leftover from previous runs.")
		}
ttt's avatar
script  
ttt committed
46 47 48 49 50 51 52 53 54 55 56 57 58 59
		if *debug {
			fmt.Println("detecting suffix")
		}
		old := 1
		for ; ; old++ {
			fmt.Println(old)
			_, err := getPubKey("oracleIdentity" + strconv.Itoa(old))
			if err != nil {
				if !strings.Contains(err.Error(), "no public key hash alias named") {
					log.Fatal(fmt.Errorf("detecting suffix: %v", err))
				}
				break
			}
		}
ttt's avatar
ttt committed
60
		// create file
ttt's avatar
ttt committed
61 62 63
		if *verbose {
			fmt.Println("Creating a file with the suffix number used for previous run.")
		}
ttt's avatar
script  
ttt committed
64 65 66 67 68 69 70 71 72 73
		if *debug {
			fmt.Println("creating file with old suffix")
		}
		s := strconv.Itoa(old - 1)
		err = ioutil.WriteFile(".setup_automated_insurance_suffix", []byte(s+"\n"), 0644)
		if err != nil {
			log.Fatal(fmt.Errorf("creating file with old suffix: %v", err))
		}
	}

ttt's avatar
ttt committed
74
	// get suffix from previous run
ttt's avatar
script  
ttt committed
75 76 77 78 79 80 81 82 83 84
	b, err := ioutil.ReadFile(".setup_automated_insurance_suffix")
	if err != nil {
		log.Fatal(fmt.Errorf("trying to read suffix file: %v", err))
	}
	scanner := bufio.NewScanner(bytes.NewReader(b))
	if !scanner.Scan() {
		log.Fatal(fmt.Errorf("reading suffix string: no string found"))
	}
	s := scanner.Text()

ttt's avatar
ttt committed
85
	// check that s contains digits only
ttt's avatar
script  
ttt committed
86 87 88 89 90 91 92 93 94 95
	for _, c := range s {
		if *debug {
			fmt.Println("character:", c)
			fmt.Printf("cast to string: %s\n", string(c))
		}
		if !unicode.IsDigit(c) {
			log.Fatal(fmt.Errorf("suffix contains non-digit characters"))
		}
	}

ttt's avatar
ttt committed
96
	// increment suffix and write back to file
ttt's avatar
script  
ttt committed
97 98 99 100 101
	old, err := strconv.Atoi(s)
	if err != nil {
		log.Fatal(fmt.Errorf("converting suffix: %v", err))
	}
	n := strconv.Itoa(old + 1)
ttt's avatar
ttt committed
102 103 104 105

	if *verbose {
		fmt.Printf("Suffix for this run is %s.\n", n)
		fmt.Println("Writing suffix to file.")
ttt's avatar
ttt committed
106
		fmt.Println("")
ttt's avatar
ttt committed
107 108
	}

ttt's avatar
script  
ttt committed
109 110 111 112 113 114 115 116 117 118 119 120
	err = ioutil.WriteFile(".setup_automated_insurance_suffix", []byte(n+"\n"), 0644)
	if err != nil {
		log.Fatal(fmt.Errorf("writing new suffix: %v", err))
	}

	oracleIdentity := "oracleIdentity" + n
	oracleContract := "oracleContract" + n
	providerIdentity := "providerIdentity" + n
	providerContract := "providerContract" + n
	redirectorContract := "redirectorContract" + n
	placeholderRedirectorContract := "placeholderRedirectorContract" + n

ttt's avatar
ttt committed
121 122
	// check whether identity with money exists

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
	// if *debug {
	// 	fmt.Println("checking money contract")
	// }
	// c := exec.Command("./tezos-client", "get", "balance", "for", "money")
	// b, err = c.CombinedOutput()
	// if err != nil {
	// 	if !strings.Contains(string(b), "Not Found") {
	// 		fmt.Println("error:", string(b))
	// 		return
	// 	}
	// 	//originate money contract if not found
	// 	if *debug {
	// 		fmt.Println(string(b))
	// 	}
	// 	if *debug {
	// 		fmt.Println("originating money contract")
	// 	}
	// 	c = exec.Command("./tezos-client", "originate", "free", "account", "money", "for", "my_identity")
	// 	b, err = c.CombinedOutput()
	// 	if err != nil {
	// 		fmt.Println("error:", string(b))
	// 		return
	// 	}
	// 	if *debug {
	// 		fmt.Println(string(b))
	// 	}
	// }
	// if *debug {
	// 	fmt.Println(string(b))
	// }
ttt's avatar
script  
ttt committed
153 154 155

	// generate oracle identity

ttt's avatar
ttt committed
156 157
	if *verbose {
		fmt.Println("Generating oracle identity.")
ttt's avatar
script  
ttt committed
158
	}
159
	c := exec.Command("./tezos-client", "gen", "keys", oracleIdentity)
ttt's avatar
script  
ttt committed
160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179
	b, err = c.CombinedOutput()
	if err != nil {
		fmt.Println("error:", string(b))
		return
	}
	if *debug {
		fmt.Println(string(b))
	}

	// get oracle public key

	oracleKey, err := getPubKey(oracleIdentity)
	if err != nil {
		log.Fatal(err)
	}

	if *debug {
		fmt.Println("oracle key:", oracleKey)
	}

180 181
	time.Sleep(70 * time.Second)

ttt's avatar
script  
ttt committed
182 183
	// originate oracle contract

ttt's avatar
ttt committed
184 185
	if *verbose {
		fmt.Println("Originating oracle contract.")
ttt's avatar
script  
ttt committed
186
	}
ttt's avatar
ttt committed
187
	// c = exec.Command("./tezos-client", "originate", "contract", oracleContract, "for", oracleIdentity, "transferring", "1000", "from", "money", "running", "oracle.tz", "-init", fmt.Sprintf(`(Pair "%s" {})`, oracleKey))
188
	c = exec.Command("./tezos-client", "originate", "contract", oracleContract, "for", oracleIdentity, "transferring", "500", "from", "money", "running", "oracle.tz", "-init", fmt.Sprintf(`(Pair "%s" {})`, oracleKey))
ttt's avatar
script  
ttt committed
189 190 191 192 193 194 195 196 197 198 199 200 201 202
	b, err = c.CombinedOutput()
	if err != nil {
		fmt.Println("error:", string(b))
		return
	}
	if *debug {
		fmt.Println(string(b))
	}

	oracleAddress, err := parseAddress(string(b))
	if err != nil {
		log.Fatal(err)
	}

203 204
	time.Sleep(70 * time.Second)

ttt's avatar
script  
ttt committed
205 206
	// generate provider identity

ttt's avatar
ttt committed
207 208
	if *verbose {
		fmt.Println("Generating provider identity.")
ttt's avatar
script  
ttt committed
209
	}
ttt's avatar
ttt committed
210
	c = exec.Command("./tezos-client", "gen", "keys", providerIdentity)
ttt's avatar
script  
ttt committed
211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226
	b, err = c.CombinedOutput()
	if err != nil {
		fmt.Println("error:", string(b))
		return
	}
	if *debug {
		fmt.Println(string(b))
	}

	// get provider public key

	providerKey, err := getPubKey(providerIdentity)
	if err != nil {
		log.Fatal(err)
	}

227 228
	time.Sleep(70 * time.Second)

ttt's avatar
script  
ttt committed
229 230
	// originate placeholder redirector contract

ttt's avatar
ttt committed
231 232
	if *verbose {
		fmt.Println("Originating placeholder redirector contract.")
ttt's avatar
script  
ttt committed
233
	}
ttt's avatar
ttt committed
234
	c = exec.Command("./tezos-client", "originate", "contract", placeholderRedirectorContract, "for", providerIdentity, "transferring", "2.00", "from", "money", "running", "placeholder_redirector.tz")
ttt's avatar
script  
ttt committed
235 236 237 238 239 240 241 242 243 244 245 246 247 248
	b, err = c.CombinedOutput()
	if err != nil {
		fmt.Println("error:", string(b))
		return
	}
	if *debug {
		fmt.Println(string(b))
	}

	placeholderRedirectorAddress, err := parseAddress(string(b))
	if err != nil {
		log.Fatal(err)
	}

249 250
	time.Sleep(70 * time.Second)

ttt's avatar
script  
ttt committed
251 252
	// originate provider contract

ttt's avatar
ttt committed
253 254 255
	if *verbose {
		fmt.Println("Originating provider contract.")
	}
ttt's avatar
script  
ttt committed
256 257 258
	if *debug {
		fmt.Println("provider key:", providerKey)
	}
259
	c = exec.Command("./tezos-client", "originate", "contract", providerContract, "for", providerIdentity, "transferring", "1000", "from", "money", "running", "provider.tz", "-init", fmt.Sprintf(`(Pair (Pair (Pair (Pair "%s" "0.00") False) (Pair "%s" "%s")) {})`, providerKey, oracleAddress, placeholderRedirectorAddress))
ttt's avatar
script  
ttt committed
260 261 262 263 264 265 266 267 268 269 270 271 272 273
	b, err = c.CombinedOutput()
	if err != nil {
		fmt.Println("error:", string(b))
		return
	}
	if *debug {
		fmt.Println(string(b))
	}

	providerAddress, err := parseAddress(string(b))
	if err != nil {
		log.Fatal(err)
	}

274 275
	time.Sleep(70 * time.Second)

ttt's avatar
script  
ttt committed
276 277
	// originate redirector contract

ttt's avatar
ttt committed
278 279
	if *verbose {
		fmt.Println("Originating redirector contract.")
ttt's avatar
script  
ttt committed
280
	}
281
	c = exec.Command("./tezos-client", "originate", "contract", redirectorContract, "for", providerIdentity, "transferring", "50", "from", "money", "running", "redirector.tz", "-init", fmt.Sprintf(`(Pair "%s" "%s")`, oracleKey, providerAddress))
ttt's avatar
script  
ttt committed
282 283 284 285 286 287 288 289 290 291 292 293 294 295
	b, err = c.CombinedOutput()
	if err != nil {
		fmt.Println("error:", string(b))
		return
	}
	if *debug {
		fmt.Println(string(b))
	}

	redirectorAddress, err := parseAddress(string(b))
	if err != nil {
		log.Fatal(err)
	}

296 297
	time.Sleep(70 * time.Second)

ttt's avatar
script  
ttt committed
298 299
	// sign redirector address

ttt's avatar
ttt committed
300
	if *verbose {
ttt's avatar
ttt committed
301
		fmt.Println("")
ttt's avatar
ttt committed
302 303 304
		fmt.Println("Signing the address of the redirector contract.")
		fmt.Println("Address:", redirectorAddress)
	}
ttt's avatar
ttt committed
305
	sig, err := signData(redirectorAddress, redirectorType, providerIdentity)
ttt's avatar
script  
ttt committed
306 307 308
	if err != nil {
		log.Fatal(err)
	}
ttt's avatar
ttt committed
309 310 311
	if *verbose {
		fmt.Println("Signature:", sig)
	}
ttt's avatar
script  
ttt committed
312

313 314
	time.Sleep(70 * time.Second)

ttt's avatar
script  
ttt committed
315 316
	// init provider with redirector address

ttt's avatar
ttt committed
317 318 319
	if *verbose {
		fmt.Println("Initializing provider contract.")
		fmt.Println("The initialization is done by sending a transaction to the provider contract, that contains the address and the signature above.")
ttt's avatar
script  
ttt committed
320
	}
321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336
	c = exec.Command("./tezos-client", "transfer", "0", "from", "money", "to", providerContract, "-arg", fmt.Sprintf(`(Left (Right (Right (Right (Pair "%s" "%s")))))`, sig, redirectorAddress))
	b, err = c.CombinedOutput()
	if err != nil {
		fmt.Println("error:", string(b))
		return
	}
	if *debug {
		fmt.Println(string(b))
	}

	// send some money to oracle identity so that it can pay tx fees

	if *verbose {
		fmt.Println("Sending money to oracle identity.")
	}
	c = exec.Command("./tezos-client", "transfer", "2000", "from", "money", "to", oracleIdentity)
ttt's avatar
script  
ttt committed
337 338 339 340 341 342 343 344 345
	b, err = c.CombinedOutput()
	if err != nil {
		fmt.Println("error:", string(b))
		return
	}
	if *debug {
		fmt.Println(string(b))
	}

346 347
	time.Sleep(70 * time.Second)

ttt's avatar
ttt committed
348
	if *verbose {
ttt's avatar
ttt committed
349
		fmt.Println("")
ttt's avatar
ttt committed
350 351 352 353
		fmt.Println("Done.")
		fmt.Println("")
		fmt.Println("Run the automated insurance server with the following information.")
		fmt.Println("Provider secret key:")
ttt's avatar
ttt committed
354 355
		c = exec.Command("./tezos-client", "show", "identity", providerIdentity, "-show-secret")

ttt's avatar
ttt committed
356 357 358 359 360 361 362
		b, err = c.CombinedOutput()
		if err != nil {
			fmt.Println("error:", string(b))
			return
		}
		fmt.Println(strings.TrimSpace(string(b)))
		fmt.Println("Provider contract:")
ttt's avatar
ttt committed
363
		c = exec.Command("./tezos-client", "show", "known", "contract", providerContract)
ttt's avatar
ttt committed
364 365 366 367 368 369 370 371 372
		b, err = c.CombinedOutput()
		if err != nil {
			fmt.Println("error:", string(b))
			return
		}
		fmt.Println(strings.TrimSpace(string(b)))
		fmt.Println("")
		fmt.Println("Run the oracle server with the following information.")
		fmt.Println("Oracle secret key:")
ttt's avatar
ttt committed
373
		c = exec.Command("./tezos-client", "show", "identity", oracleIdentity, "-show-secret")
ttt's avatar
ttt committed
374 375 376 377 378 379 380
		b, err = c.CombinedOutput()
		if err != nil {
			fmt.Println("error:", string(b))
			return
		}
		fmt.Println(strings.TrimSpace(string(b)))
		fmt.Println("Oracle contract:")
ttt's avatar
ttt committed
381
		c = exec.Command("./tezos-client", "show", "known", "contract", oracleContract)
ttt's avatar
ttt committed
382 383 384 385 386 387 388 389
		b, err = c.CombinedOutput()
		if err != nil {
			fmt.Println("error:", string(b))
			return
		}
		fmt.Println(strings.TrimSpace(string(b)))
	}

ttt's avatar
script  
ttt committed
390 391 392 393 394 395 396 397 398 399
	// start oracle server

	// start insurance quote server

}

func getPubKey(alias string) (string, error) {
	if *debug {
		fmt.Println("getting public key for:", alias)
	}
ttt's avatar
ttt committed
400
	c := exec.Command("./tezos-client", "show", "identity", alias)
ttt's avatar
script  
ttt committed
401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430
	b, err := c.CombinedOutput()
	if err != nil {
		return "", fmt.Errorf("running commands to get public key: %v", string(b))
	}
	if *debug {
		fmt.Println(string(b))
	}
	key, err := parsePubKey(string(b))
	if err != nil {
		return "", fmt.Errorf("getting public key for identity %s: %v", alias, err)
	}
	return key, nil
}

// sudo ./alphanet.sh client gen keys user9
// Hash: tz1hH75KCasF3PbKKpf4gqWyCTbXfBNd2kre
// Public Key: edpkvW6X5c4v49updTupd5xivwYd55m92UsctS9XCYDpCU6BtFQShy

func parsePubKey(output string) (string, error) {
	lines := strings.Split(strings.TrimSpace(output), "\n")
	for _, l := range lines {
		if strings.Contains(l, "Public Key:") {
			parts := strings.Split(strings.TrimSpace(l), ": ")
			// ["Public Key", "edpkvW6X5c4v49updTupd5xivwYd55m92UsctS9XCYDpCU6BtFQShy"]
			return parts[1], nil
		}
	}
	return "", fmt.Errorf("parsing public key: no key detected")
}

ttt's avatar
ttt committed
431
func signData(data, dataType, identity string) (string, error) {
ttt's avatar
script  
ttt committed
432 433 434
	if *debug {
		fmt.Println("signing data:", data)
	}
ttt's avatar
ttt committed
435
	c := exec.Command("./tezos-client", "hash", "and", "sign", "data", fmt.Sprintf(`"%s"`, data), "of", "type", dataType, "for", identity)
ttt's avatar
script  
ttt committed
436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482
	b, err := c.CombinedOutput()
	if err != nil {
		fmt.Println("error:", string(b))
		return "", fmt.Errorf("running commands to sign: %v", err)
	}
	if *debug {
		fmt.Println(string(b))
	}
	lines := strings.Split(string(b), "\n")
	for _, l := range lines {
		l := strings.TrimSpace(l)
		if strings.HasPrefix(l, "Signature:") {
			words := strings.Split(l, " ")
			signature := strings.Trim(strings.TrimSpace(words[1]), `"`)
			if *debug {
				fmt.Println("signature parsed as:", signature)
			}
			return signature, nil
		}
	}
	return "", fmt.Errorf("parsing output: signature not found")
}

// Got the source's manager keys (my_identity).
// Operation successfully injected in the node.
// Operation hash is 'ooULTAehpho6wrdMzfCioymdwXz5eXpP28LYw9Fe3Y47e1nKTjS'.
// New contract TZ1hJVq4xj6zjwS2H63wozDvvSbqXeK6Xg6A originated from a smart contract.
// New contract alias 'testDA' saved.
// Contract memorized as testDA.

func parseAddress(output string) (string, error) {
	lines := strings.Split(strings.TrimSpace(output), "\n")
	for _, l := range lines {
		if strings.Contains(l, "originated from a smart contract") {
			parts := strings.Split(strings.TrimSpace(l), " ")
			// ["New", "contract", "TZ1hJVq4xj6zjwS2H63wozDvvSbqXeK6Xg6A", "originated", "from", "a", "smart", "contract."]
			for _, p := range parts {
				//trim whitespace just in case
				p = strings.TrimSpace(p)
				if strings.HasPrefix(p, "TZ1") {
					return p, nil
				}
			}
		}
	}
	return "", fmt.Errorf("parsing address: no address detected")
}