github.com/Cleverse/go-ethereum@v0.0.0-20220927095127-45113064e7f2/accounts/abi/bind/bind.go (about) 1 // Copyright 2016 The go-ethereum Authors 2 // This file is part of the go-ethereum library. 3 // 4 // The go-ethereum library is free software: you can redistribute it and/or modify 5 // it under the terms of the GNU Lesser General Public License as published by 6 // the Free Software Foundation, either version 3 of the License, or 7 // (at your option) any later version. 8 // 9 // The go-ethereum library is distributed in the hope that it will be useful, 10 // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 // GNU Lesser General Public License for more details. 13 // 14 // You should have received a copy of the GNU Lesser General Public License 15 // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>. 16 17 // Package bind generates Ethereum contract Go bindings. 18 // 19 // Detailed usage document and tutorial available on the go-ethereum Wiki page: 20 // https://github.com/ethereum/go-ethereum/wiki/Native-DApps:-Go-bindings-to-Ethereum-contracts 21 package bind 22 23 import ( 24 "bytes" 25 "errors" 26 "fmt" 27 "go/format" 28 "regexp" 29 "strings" 30 "text/template" 31 "unicode" 32 33 "github.com/ethereum/go-ethereum/accounts/abi" 34 "github.com/ethereum/go-ethereum/log" 35 ) 36 37 // Lang is a target programming language selector to generate bindings for. 38 type Lang int 39 40 const ( 41 LangGo Lang = iota 42 LangJava 43 LangObjC 44 ) 45 46 func isKeyWord(arg string) bool { 47 switch arg { 48 case "break": 49 case "case": 50 case "chan": 51 case "const": 52 case "continue": 53 case "default": 54 case "defer": 55 case "else": 56 case "fallthrough": 57 case "for": 58 case "func": 59 case "go": 60 case "goto": 61 case "if": 62 case "import": 63 case "interface": 64 case "iota": 65 case "map": 66 case "make": 67 case "new": 68 case "package": 69 case "range": 70 case "return": 71 case "select": 72 case "struct": 73 case "switch": 74 case "type": 75 case "var": 76 default: 77 return false 78 } 79 80 return true 81 } 82 83 // Bind generates a Go wrapper around a contract ABI. This wrapper isn't meant 84 // to be used as is in client code, but rather as an intermediate struct which 85 // enforces compile time type safety and naming convention opposed to having to 86 // manually maintain hard coded strings that break on runtime. 87 func Bind(types []string, abis []string, bytecodes []string, fsigs []map[string]string, pkg string, lang Lang, libs map[string]string, aliases map[string]string) (string, error) { 88 var ( 89 // contracts is the map of each individual contract requested binding 90 contracts = make(map[string]*tmplContract) 91 92 // structs is the map of all redeclared structs shared by passed contracts. 93 structs = make(map[string]*tmplStruct) 94 95 // isLib is the map used to flag each encountered library as such 96 isLib = make(map[string]struct{}) 97 ) 98 for i := 0; i < len(types); i++ { 99 // Parse the actual ABI to generate the binding for 100 evmABI, err := abi.JSON(strings.NewReader(abis[i])) 101 if err != nil { 102 return "", err 103 } 104 // Strip any whitespace from the JSON ABI 105 strippedABI := strings.Map(func(r rune) rune { 106 if unicode.IsSpace(r) { 107 return -1 108 } 109 return r 110 }, abis[i]) 111 112 // Extract the call and transact methods; events, struct definitions; and sort them alphabetically 113 var ( 114 calls = make(map[string]*tmplMethod) 115 transacts = make(map[string]*tmplMethod) 116 events = make(map[string]*tmplEvent) 117 fallback *tmplMethod 118 receive *tmplMethod 119 120 // identifiers are used to detect duplicated identifiers of functions 121 // and events. For all calls, transacts and events, abigen will generate 122 // corresponding bindings. However we have to ensure there is no 123 // identifier collisions in the bindings of these categories. 124 callIdentifiers = make(map[string]bool) 125 transactIdentifiers = make(map[string]bool) 126 eventIdentifiers = make(map[string]bool) 127 ) 128 129 for _, input := range evmABI.Constructor.Inputs { 130 if hasStruct(input.Type) { 131 bindStructType[lang](input.Type, structs) 132 } 133 } 134 135 for _, original := range evmABI.Methods { 136 // Normalize the method for capital cases and non-anonymous inputs/outputs 137 normalized := original 138 normalizedName := methodNormalizer[lang](alias(aliases, original.Name)) 139 140 // Ensure there is no duplicated identifier 141 var identifiers = callIdentifiers 142 if !original.IsConstant() { 143 identifiers = transactIdentifiers 144 } 145 if identifiers[normalizedName] { 146 return "", fmt.Errorf("duplicated identifier \"%s\"(normalized \"%s\"), use --alias for renaming", original.Name, normalizedName) 147 } 148 identifiers[normalizedName] = true 149 150 normalized.Name = normalizedName 151 normalized.Inputs = make([]abi.Argument, len(original.Inputs)) 152 copy(normalized.Inputs, original.Inputs) 153 for j, input := range normalized.Inputs { 154 if input.Name == "" || isKeyWord(input.Name) { 155 normalized.Inputs[j].Name = fmt.Sprintf("arg%d", j) 156 } 157 if hasStruct(input.Type) { 158 bindStructType[lang](input.Type, structs) 159 } 160 } 161 normalized.Outputs = make([]abi.Argument, len(original.Outputs)) 162 copy(normalized.Outputs, original.Outputs) 163 for j, output := range normalized.Outputs { 164 if output.Name != "" { 165 normalized.Outputs[j].Name = capitalise(output.Name) 166 } 167 if hasStruct(output.Type) { 168 bindStructType[lang](output.Type, structs) 169 } 170 } 171 // Append the methods to the call or transact lists 172 if original.IsConstant() { 173 calls[original.Name] = &tmplMethod{Original: original, Normalized: normalized, Structured: structured(original.Outputs)} 174 } else { 175 transacts[original.Name] = &tmplMethod{Original: original, Normalized: normalized, Structured: structured(original.Outputs)} 176 } 177 } 178 for _, original := range evmABI.Events { 179 // Skip anonymous events as they don't support explicit filtering 180 if original.Anonymous { 181 continue 182 } 183 // Normalize the event for capital cases and non-anonymous outputs 184 normalized := original 185 186 // Ensure there is no duplicated identifier 187 normalizedName := methodNormalizer[lang](alias(aliases, original.Name)) 188 if eventIdentifiers[normalizedName] { 189 return "", fmt.Errorf("duplicated identifier \"%s\"(normalized \"%s\"), use --alias for renaming", original.Name, normalizedName) 190 } 191 eventIdentifiers[normalizedName] = true 192 normalized.Name = normalizedName 193 194 used := make(map[string]bool) 195 normalized.Inputs = make([]abi.Argument, len(original.Inputs)) 196 copy(normalized.Inputs, original.Inputs) 197 for j, input := range normalized.Inputs { 198 if input.Name == "" || isKeyWord(input.Name) { 199 normalized.Inputs[j].Name = fmt.Sprintf("arg%d", j) 200 } 201 // Event is a bit special, we need to define event struct in binding, 202 // ensure there is no camel-case-style name conflict. 203 for index := 0; ; index++ { 204 if !used[capitalise(normalized.Inputs[j].Name)] { 205 used[capitalise(normalized.Inputs[j].Name)] = true 206 break 207 } 208 normalized.Inputs[j].Name = fmt.Sprintf("%s%d", normalized.Inputs[j].Name, index) 209 } 210 if hasStruct(input.Type) { 211 bindStructType[lang](input.Type, structs) 212 } 213 } 214 // Append the event to the accumulator list 215 events[original.Name] = &tmplEvent{Original: original, Normalized: normalized} 216 } 217 // Add two special fallback functions if they exist 218 if evmABI.HasFallback() { 219 fallback = &tmplMethod{Original: evmABI.Fallback} 220 } 221 if evmABI.HasReceive() { 222 receive = &tmplMethod{Original: evmABI.Receive} 223 } 224 // There is no easy way to pass arbitrary java objects to the Go side. 225 if len(structs) > 0 && lang == LangJava { 226 return "", errors.New("java binding for tuple arguments is not supported yet") 227 } 228 229 contracts[types[i]] = &tmplContract{ 230 Type: capitalise(types[i]), 231 InputABI: strings.ReplaceAll(strippedABI, "\"", "\\\""), 232 InputBin: strings.TrimPrefix(strings.TrimSpace(bytecodes[i]), "0x"), 233 Constructor: evmABI.Constructor, 234 Calls: calls, 235 Transacts: transacts, 236 Fallback: fallback, 237 Receive: receive, 238 Events: events, 239 Libraries: make(map[string]string), 240 } 241 // Function 4-byte signatures are stored in the same sequence 242 // as types, if available. 243 if len(fsigs) > i { 244 contracts[types[i]].FuncSigs = fsigs[i] 245 } 246 // Parse library references. 247 for pattern, name := range libs { 248 matched, err := regexp.Match("__\\$"+pattern+"\\$__", []byte(contracts[types[i]].InputBin)) 249 if err != nil { 250 log.Error("Could not search for pattern", "pattern", pattern, "contract", contracts[types[i]], "err", err) 251 } 252 if matched { 253 contracts[types[i]].Libraries[pattern] = name 254 // keep track that this type is a library 255 if _, ok := isLib[name]; !ok { 256 isLib[name] = struct{}{} 257 } 258 } 259 } 260 } 261 // Check if that type has already been identified as a library 262 for i := 0; i < len(types); i++ { 263 _, ok := isLib[types[i]] 264 contracts[types[i]].Library = ok 265 } 266 // Generate the contract template data content and render it 267 data := &tmplData{ 268 Package: pkg, 269 Contracts: contracts, 270 Libraries: libs, 271 Structs: structs, 272 } 273 buffer := new(bytes.Buffer) 274 275 funcs := map[string]interface{}{ 276 "bindtype": bindType[lang], 277 "bindtopictype": bindTopicType[lang], 278 "namedtype": namedType[lang], 279 "capitalise": capitalise, 280 "decapitalise": decapitalise, 281 } 282 tmpl := template.Must(template.New("").Funcs(funcs).Parse(tmplSource[lang])) 283 if err := tmpl.Execute(buffer, data); err != nil { 284 return "", err 285 } 286 // For Go bindings pass the code through gofmt to clean it up 287 if lang == LangGo { 288 code, err := format.Source(buffer.Bytes()) 289 if err != nil { 290 return "", fmt.Errorf("%v\n%s", err, buffer) 291 } 292 return string(code), nil 293 } 294 // For all others just return as is for now 295 return buffer.String(), nil 296 } 297 298 // bindType is a set of type binders that convert Solidity types to some supported 299 // programming language types. 300 var bindType = map[Lang]func(kind abi.Type, structs map[string]*tmplStruct) string{ 301 LangGo: bindTypeGo, 302 LangJava: bindTypeJava, 303 } 304 305 // bindBasicTypeGo converts basic solidity types(except array, slice and tuple) to Go ones. 306 func bindBasicTypeGo(kind abi.Type) string { 307 switch kind.T { 308 case abi.AddressTy: 309 return "common.Address" 310 case abi.IntTy, abi.UintTy: 311 parts := regexp.MustCompile(`(u)?int([0-9]*)`).FindStringSubmatch(kind.String()) 312 switch parts[2] { 313 case "8", "16", "32", "64": 314 return fmt.Sprintf("%sint%s", parts[1], parts[2]) 315 } 316 return "*big.Int" 317 case abi.FixedBytesTy: 318 return fmt.Sprintf("[%d]byte", kind.Size) 319 case abi.BytesTy: 320 return "[]byte" 321 case abi.FunctionTy: 322 return "[24]byte" 323 default: 324 // string, bool types 325 return kind.String() 326 } 327 } 328 329 // bindTypeGo converts solidity types to Go ones. Since there is no clear mapping 330 // from all Solidity types to Go ones (e.g. uint17), those that cannot be exactly 331 // mapped will use an upscaled type (e.g. BigDecimal). 332 func bindTypeGo(kind abi.Type, structs map[string]*tmplStruct) string { 333 switch kind.T { 334 case abi.TupleTy: 335 return structs[kind.TupleRawName+kind.String()].Name 336 case abi.ArrayTy: 337 return fmt.Sprintf("[%d]", kind.Size) + bindTypeGo(*kind.Elem, structs) 338 case abi.SliceTy: 339 return "[]" + bindTypeGo(*kind.Elem, structs) 340 default: 341 return bindBasicTypeGo(kind) 342 } 343 } 344 345 // bindBasicTypeJava converts basic solidity types(except array, slice and tuple) to Java ones. 346 func bindBasicTypeJava(kind abi.Type) string { 347 switch kind.T { 348 case abi.AddressTy: 349 return "Address" 350 case abi.IntTy, abi.UintTy: 351 // Note that uint and int (without digits) are also matched, 352 // these are size 256, and will translate to BigInt (the default). 353 parts := regexp.MustCompile(`(u)?int([0-9]*)`).FindStringSubmatch(kind.String()) 354 if len(parts) != 3 { 355 return kind.String() 356 } 357 // All unsigned integers should be translated to BigInt since gomobile doesn't 358 // support them. 359 if parts[1] == "u" { 360 return "BigInt" 361 } 362 363 namedSize := map[string]string{ 364 "8": "byte", 365 "16": "short", 366 "32": "int", 367 "64": "long", 368 }[parts[2]] 369 370 // default to BigInt 371 if namedSize == "" { 372 namedSize = "BigInt" 373 } 374 return namedSize 375 case abi.FixedBytesTy, abi.BytesTy: 376 return "byte[]" 377 case abi.BoolTy: 378 return "boolean" 379 case abi.StringTy: 380 return "String" 381 case abi.FunctionTy: 382 return "byte[24]" 383 default: 384 return kind.String() 385 } 386 } 387 388 // pluralizeJavaType explicitly converts multidimensional types to predefined 389 // types in go side. 390 func pluralizeJavaType(typ string) string { 391 switch typ { 392 case "boolean": 393 return "Bools" 394 case "String": 395 return "Strings" 396 case "Address": 397 return "Addresses" 398 case "byte[]": 399 return "Binaries" 400 case "BigInt": 401 return "BigInts" 402 } 403 return typ + "[]" 404 } 405 406 // bindTypeJava converts a Solidity type to a Java one. Since there is no clear mapping 407 // from all Solidity types to Java ones (e.g. uint17), those that cannot be exactly 408 // mapped will use an upscaled type (e.g. BigDecimal). 409 func bindTypeJava(kind abi.Type, structs map[string]*tmplStruct) string { 410 switch kind.T { 411 case abi.TupleTy: 412 return structs[kind.TupleRawName+kind.String()].Name 413 case abi.ArrayTy, abi.SliceTy: 414 return pluralizeJavaType(bindTypeJava(*kind.Elem, structs)) 415 default: 416 return bindBasicTypeJava(kind) 417 } 418 } 419 420 // bindTopicType is a set of type binders that convert Solidity types to some 421 // supported programming language topic types. 422 var bindTopicType = map[Lang]func(kind abi.Type, structs map[string]*tmplStruct) string{ 423 LangGo: bindTopicTypeGo, 424 LangJava: bindTopicTypeJava, 425 } 426 427 // bindTopicTypeGo converts a Solidity topic type to a Go one. It is almost the same 428 // functionality as for simple types, but dynamic types get converted to hashes. 429 func bindTopicTypeGo(kind abi.Type, structs map[string]*tmplStruct) string { 430 bound := bindTypeGo(kind, structs) 431 432 // todo(rjl493456442) according solidity documentation, indexed event 433 // parameters that are not value types i.e. arrays and structs are not 434 // stored directly but instead a keccak256-hash of an encoding is stored. 435 // 436 // We only convert stringS and bytes to hash, still need to deal with 437 // array(both fixed-size and dynamic-size) and struct. 438 if bound == "string" || bound == "[]byte" { 439 bound = "common.Hash" 440 } 441 return bound 442 } 443 444 // bindTopicTypeJava converts a Solidity topic type to a Java one. It is almost the same 445 // functionality as for simple types, but dynamic types get converted to hashes. 446 func bindTopicTypeJava(kind abi.Type, structs map[string]*tmplStruct) string { 447 bound := bindTypeJava(kind, structs) 448 449 // todo(rjl493456442) according solidity documentation, indexed event 450 // parameters that are not value types i.e. arrays and structs are not 451 // stored directly but instead a keccak256-hash of an encoding is stored. 452 // 453 // We only convert strings and bytes to hash, still need to deal with 454 // array(both fixed-size and dynamic-size) and struct. 455 if bound == "String" || bound == "byte[]" { 456 bound = "Hash" 457 } 458 return bound 459 } 460 461 // bindStructType is a set of type binders that convert Solidity tuple types to some supported 462 // programming language struct definition. 463 var bindStructType = map[Lang]func(kind abi.Type, structs map[string]*tmplStruct) string{ 464 LangGo: bindStructTypeGo, 465 LangJava: bindStructTypeJava, 466 } 467 468 // bindStructTypeGo converts a Solidity tuple type to a Go one and records the mapping 469 // in the given map. 470 // Notably, this function will resolve and record nested struct recursively. 471 func bindStructTypeGo(kind abi.Type, structs map[string]*tmplStruct) string { 472 switch kind.T { 473 case abi.TupleTy: 474 // We compose a raw struct name and a canonical parameter expression 475 // together here. The reason is before solidity v0.5.11, kind.TupleRawName 476 // is empty, so we use canonical parameter expression to distinguish 477 // different struct definition. From the consideration of backward 478 // compatibility, we concat these two together so that if kind.TupleRawName 479 // is not empty, it can have unique id. 480 id := kind.TupleRawName + kind.String() 481 if s, exist := structs[id]; exist { 482 return s.Name 483 } 484 var ( 485 names = make(map[string]bool) 486 fields []*tmplField 487 ) 488 for i, elem := range kind.TupleElems { 489 name := capitalise(kind.TupleRawNames[i]) 490 name = abi.ResolveNameConflict(name, func(s string) bool { return names[s] }) 491 names[name] = true 492 fields = append(fields, &tmplField{Type: bindStructTypeGo(*elem, structs), Name: name, SolKind: *elem}) 493 } 494 name := kind.TupleRawName 495 if name == "" { 496 name = fmt.Sprintf("Struct%d", len(structs)) 497 } 498 name = capitalise(name) 499 500 structs[id] = &tmplStruct{ 501 Name: name, 502 Fields: fields, 503 } 504 return name 505 case abi.ArrayTy: 506 return fmt.Sprintf("[%d]", kind.Size) + bindStructTypeGo(*kind.Elem, structs) 507 case abi.SliceTy: 508 return "[]" + bindStructTypeGo(*kind.Elem, structs) 509 default: 510 return bindBasicTypeGo(kind) 511 } 512 } 513 514 // bindStructTypeJava converts a Solidity tuple type to a Java one and records the mapping 515 // in the given map. 516 // Notably, this function will resolve and record nested struct recursively. 517 func bindStructTypeJava(kind abi.Type, structs map[string]*tmplStruct) string { 518 switch kind.T { 519 case abi.TupleTy: 520 // We compose a raw struct name and a canonical parameter expression 521 // together here. The reason is before solidity v0.5.11, kind.TupleRawName 522 // is empty, so we use canonical parameter expression to distinguish 523 // different struct definition. From the consideration of backward 524 // compatibility, we concat these two together so that if kind.TupleRawName 525 // is not empty, it can have unique id. 526 id := kind.TupleRawName + kind.String() 527 if s, exist := structs[id]; exist { 528 return s.Name 529 } 530 var fields []*tmplField 531 for i, elem := range kind.TupleElems { 532 field := bindStructTypeJava(*elem, structs) 533 fields = append(fields, &tmplField{Type: field, Name: decapitalise(kind.TupleRawNames[i]), SolKind: *elem}) 534 } 535 name := kind.TupleRawName 536 if name == "" { 537 name = fmt.Sprintf("Class%d", len(structs)) 538 } 539 structs[id] = &tmplStruct{ 540 Name: name, 541 Fields: fields, 542 } 543 return name 544 case abi.ArrayTy, abi.SliceTy: 545 return pluralizeJavaType(bindStructTypeJava(*kind.Elem, structs)) 546 default: 547 return bindBasicTypeJava(kind) 548 } 549 } 550 551 // namedType is a set of functions that transform language specific types to 552 // named versions that may be used inside method names. 553 var namedType = map[Lang]func(string, abi.Type) string{ 554 LangGo: func(string, abi.Type) string { panic("this shouldn't be needed") }, 555 LangJava: namedTypeJava, 556 } 557 558 // namedTypeJava converts some primitive data types to named variants that can 559 // be used as parts of method names. 560 func namedTypeJava(javaKind string, solKind abi.Type) string { 561 switch javaKind { 562 case "byte[]": 563 return "Binary" 564 case "boolean": 565 return "Bool" 566 default: 567 parts := regexp.MustCompile(`(u)?int([0-9]*)(\[[0-9]*\])?`).FindStringSubmatch(solKind.String()) 568 if len(parts) != 4 { 569 return javaKind 570 } 571 switch parts[2] { 572 case "8", "16", "32", "64": 573 if parts[3] == "" { 574 return capitalise(fmt.Sprintf("%sint%s", parts[1], parts[2])) 575 } 576 return capitalise(fmt.Sprintf("%sint%ss", parts[1], parts[2])) 577 578 default: 579 return javaKind 580 } 581 } 582 } 583 584 // alias returns an alias of the given string based on the aliasing rules 585 // or returns itself if no rule is matched. 586 func alias(aliases map[string]string, n string) string { 587 if alias, exist := aliases[n]; exist { 588 return alias 589 } 590 return n 591 } 592 593 // methodNormalizer is a name transformer that modifies Solidity method names to 594 // conform to target language naming conventions. 595 var methodNormalizer = map[Lang]func(string) string{ 596 LangGo: abi.ToCamelCase, 597 LangJava: decapitalise, 598 } 599 600 // capitalise makes a camel-case string which starts with an upper case character. 601 var capitalise = abi.ToCamelCase 602 603 // decapitalise makes a camel-case string which starts with a lower case character. 604 func decapitalise(input string) string { 605 if len(input) == 0 { 606 return input 607 } 608 609 goForm := abi.ToCamelCase(input) 610 return strings.ToLower(goForm[:1]) + goForm[1:] 611 } 612 613 // structured checks whether a list of ABI data types has enough information to 614 // operate through a proper Go struct or if flat returns are needed. 615 func structured(args abi.Arguments) bool { 616 if len(args) < 2 { 617 return false 618 } 619 exists := make(map[string]bool) 620 for _, out := range args { 621 // If the name is anonymous, we can't organize into a struct 622 if out.Name == "" { 623 return false 624 } 625 // If the field name is empty when normalized or collides (var, Var, _var, _Var), 626 // we can't organize into a struct 627 field := capitalise(out.Name) 628 if field == "" || exists[field] { 629 return false 630 } 631 exists[field] = true 632 } 633 return true 634 } 635 636 // hasStruct returns an indicator whether the given type is struct, struct slice 637 // or struct array. 638 func hasStruct(t abi.Type) bool { 639 switch t.T { 640 case abi.SliceTy: 641 return hasStruct(*t.Elem) 642 case abi.ArrayTy: 643 return hasStruct(*t.Elem) 644 case abi.TupleTy: 645 return true 646 default: 647 return false 648 } 649 }