├── .github └── workflows │ └── pr-checks.yml ├── .golangci.yml ├── LICENSE ├── README.md ├── audit_report.pdf ├── batch.go ├── batch_test.go ├── bip39.go ├── bip39_test.go ├── derive.go ├── derive_test.go ├── example_test.go ├── go.mod ├── go.sum ├── helpers.go ├── keys.go ├── keys_test.go ├── sign.go ├── sign_test.go ├── vrf.go └── vrf_test.go /.github/workflows/pr-checks.yml: -------------------------------------------------------------------------------- 1 | on: [pull_request] 2 | name: pr-checks 3 | 4 | jobs: 5 | golangci: 6 | runs-on: ubuntu-latest 7 | steps: 8 | - uses: actions/checkout@v4 9 | - uses: actions/setup-go@v5 10 | with: 11 | go-version-file: ./go.mod 12 | - name: golangci-lint 13 | uses: golangci/golangci-lint-action@v6 14 | with: 15 | version: v1.60 16 | args: --timeout 5m 17 | unit-tests: 18 | strategy: 19 | matrix: 20 | platform: [macos-latest, ubuntu-latest] 21 | runs-on: ${{ matrix.platform }} 22 | steps: 23 | - uses: actions/checkout@v4 24 | - uses: actions/setup-go@v5 25 | with: 26 | go-version-file: ./go.mod 27 | - name: Run unit tests 28 | run: go test ./... -v 29 | -------------------------------------------------------------------------------- /.golangci.yml: -------------------------------------------------------------------------------- 1 | # Copyright 2020 ChainSafe Systems 2 | # SPDX-License-Identifier: LGPL-3.0-only 3 | 4 | # Source: https://github.com/golangci/golangci-lint/blob/master/.golangci.example.yml 5 | # options for analysis running 6 | run: 7 | # default concurrency is a available CPU number 8 | concurrency: 4 9 | 10 | # exit code when at least one issue was found, default is 1 11 | issues-exit-code: 1 12 | 13 | # include test files or not, default is true 14 | tests: true 15 | 16 | # list of build tags, all linters use it. Default is empty list. 17 | #build-tags: 18 | 19 | # which dirs to skip: they won't be analyzed; 20 | # can use regexp here: generated.*, regexp is applied on full path; 21 | # default value is empty list, but next dirs are always skipped independently 22 | # from this option's value: 23 | # vendor$, third_party$, testdata$, examples$, Godeps$, builtin$ 24 | #skip-dirs: 25 | 26 | # which files to skip: they will be analyzed, but issues from them 27 | # won't be reported. Default value is empty list, but there is 28 | # no need to include all autogenerated files, we confidently recognize 29 | # autogenerated files. If it's not please let us know. 30 | #skip-files: 31 | 32 | # by default isn't set. If set we pass it to "go list -mod={option}". From "go help modules": 33 | # If invoked with -mod=readonly, the go command is disallowed from the implicit 34 | # automatic updating of go.mod described above. Instead, it fails when any changes 35 | # to go.mod are needed. This setting is most useful to check that go.mod does 36 | # not need updates, such as in a continuous integration and testing system. 37 | # If invoked with -mod=vendor, the go command assumes that the vendor 38 | # directory holds the correct copies of dependencies and ignores 39 | # the dependency descriptions in go.mod. 40 | #modules-download-mode: (release|readonly|vendor) 41 | 42 | 43 | # output configuration options 44 | output: 45 | 46 | # print lines of code with issue, default is true 47 | print-issued-lines: true 48 | 49 | # print linter name in the end of issue text, default is true 50 | print-linter-name: true 51 | 52 | 53 | # all available settings of specific linters 54 | linters-settings: 55 | errcheck: 56 | # report about not checking of errors in type assetions: `a := b.(MyStruct)`; 57 | # default is false: such cases aren't reported by default. 58 | check-type-assertions: true 59 | 60 | # report about assignment of errors to blank identifier: `num, _ := strconv.Atoi(numStr)`; 61 | # default is false: such cases aren't reported by default. 62 | check-blank: false 63 | 64 | # path to a file containing a list of functions to exclude from checking 65 | # see https://github.com/kisielk/errcheck#excluding-functions for details 66 | #exclude: /path/to/file.txt 67 | govet: 68 | # report about shadowed variables 69 | 70 | # settings per analyzer 71 | settings: 72 | printf: # analyzer name, run `go tool vet help` to see all analyzers 73 | funcs: # run `go tool vet help printf` to see available settings for `printf` analyzer 74 | - (github.com/golangci/golangci-lint/pkg/logutils.Log).Infof 75 | - (github.com/golangci/golangci-lint/pkg/logutils.Log).Warnf 76 | - (github.com/golangci/golangci-lint/pkg/logutils.Log).Errorf 77 | - (github.com/golangci/golangci-lint/pkg/logutils.Log).Fatalf 78 | gofmt: 79 | # simplify code: gofmt with `-s` option, true by default 80 | simplify: true 81 | goimports: 82 | # put imports beginning with prefix after 3rd-party packages; 83 | # it's a comma-separated list of prefixes 84 | #local-prefixes: github.com/org/project 85 | gocyclo: 86 | # minimal code complexity to report, 30 by default (but we recommend 10-20) 87 | min-complexity: 10 88 | dupl: 89 | # tokens count to trigger issue, 150 by default 90 | threshold: 100 91 | goconst: 92 | # minimal length of string constant, 3 by default 93 | min-len: 3 94 | # minimal occurrences count to trigger, 3 by default 95 | min-occurrences: 3 96 | misspell: 97 | # Correct spellings using locale preferences for US or UK. 98 | # Default is to use a neutral variety of English. 99 | # Setting locale to US will correct the British spelling of 'colour' to 'color'. 100 | locale: US 101 | lll: 102 | # max line length, lines longer will be reported. Default is 120. 103 | # '\t' is counted as 1 character by default, and can be changed with the tab-width option 104 | line-length: 120 105 | # tab width in spaces. Default to 1. 106 | tab-width: 1 107 | unparam: 108 | # Inspect exported functions, default is false. Set to true if no external program/library imports your code. 109 | # XXX: if you enable this setting, unparam will report a lot of false-positives in text editors: 110 | # if it's called for subdir of a project it can't find external interfaces. All text editor integrations 111 | # with golangci-lint call it on a directory with the changed file. 112 | check-exported: false 113 | nakedret: 114 | # make an issue if func has more lines of code than this setting and it has naked returns; default is 30 115 | max-func-lines: 30 116 | prealloc: 117 | # XXX: we don't recommend using this linter before doing performance profiling. 118 | # For most programs usage of prealloc will be a premature optimization. 119 | 120 | # Report preallocation suggestions only on simple loops that have no returns/breaks/continues/gotos in them. 121 | # True by default. 122 | simple: true 123 | range-loops: true # Report preallocation suggestions on range loops, true by default 124 | for-loops: false # Report preallocation suggestions on for loops, false by default 125 | gocritic: 126 | # Which checks should be disabled; can't be combined with 'enabled-checks'; default is empty 127 | disabled-checks: 128 | - regexpMust 129 | 130 | # Enable multiple checks by tags, run `GL_DEBUG=gocritic golangci-lint` run to see all tags and checks. 131 | # Empty list by default. See https://github.com/go-critic/go-critic#usage -> section "Tags". 132 | enabled-tags: 133 | - performance 134 | 135 | settings: # settings passed to gocritic 136 | captLocal: # must be valid enabled check name 137 | paramsOnly: true 138 | rangeValCopy: 139 | sizeThreshold: 32 140 | 141 | linters: 142 | enable: 143 | - staticcheck 144 | - unused 145 | - gosimple 146 | - govet 147 | - gofmt 148 | - goimports 149 | - gosec 150 | - errcheck 151 | # - testpackage 152 | enable-all: false 153 | disable: 154 | - prealloc 155 | - unparam 156 | disable-all: false 157 | presets: 158 | - bugs 159 | - unused 160 | fast: false 161 | 162 | 163 | issues: 164 | # List of regexps of issue texts to exclude, empty list by default. 165 | # But independently from this option we use default exclude patterns, 166 | # it can be disabled by `exclude-use-default: false`. To list all 167 | # excluded by default patterns execute `golangci-lint run --help` 168 | #exclude: 169 | 170 | # Excluding configuration per-path, per-linter, per-text and per-source 171 | exclude-rules: 172 | # Exclude some linters from running on tests files. 173 | - path: _test\.go 174 | linters: 175 | - gocyclo 176 | - errcheck 177 | - dupl 178 | - gosec 179 | - golint 180 | 181 | # Exclude known linters from partially hard-vendored code, 182 | # which is impossible to exclude via "nolint" comments. 183 | - path: internal/hmac/ 184 | text: "weak cryptographic primitive" 185 | linters: 186 | - gosec 187 | 188 | # Exclude some staticcheck messages 189 | - linters: 190 | - staticcheck 191 | text: "SA9003:" 192 | 193 | # Exclude lll issues for long lines with go:generate 194 | - linters: 195 | - lll 196 | source: "^//go:generate " 197 | text: "long-lines" 198 | 199 | # Independently from option `exclude` we use default exclude patterns, 200 | # it can be disabled by this option. To list all 201 | # excluded by default patterns execute `golangci-lint run --help`. 202 | # Default value for this option is true. 203 | exclude-use-default: false 204 | 205 | # Maximum count of issues with the same text. Set to 0 to disable. Default is 3. 206 | max-same-issues: 0 207 | 208 | # Show only new issues: if there are unstaged changes or untracked files, 209 | # only those changes are analyzed, else only changes in HEAD~ are analyzed. 210 | # It's a super-useful option for integration of golangci-lint into existing 211 | # large codebase. It's not practical to fix all existing issues at the moment 212 | # of integration: much better don't allow issues in new code. 213 | # Default is false. 214 | new: false 215 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # go-schnorrkel 2 | 3 | Discord 4 | 5 | 6 | 7 | This repo contains the Go implementation of the sr25519 signature algorithm (schnorr over ristretto25519). The existing Rust implementation is [here.](https://github.com/w3f/schnorrkel) 8 | 9 | This library is currently able to create sr25519 keys, import sr25519 keys, and sign and verify messages. It is interoperable with the Rust implementation. 10 | 11 | The BIP39 implementation in this library is compatible with the rust [substrate-bip39](https://github.com/paritytech/substrate-bip39) implementation. Note that this is not a standard bip39 implementation. 12 | 13 | This library has been audited as of August 2021 and is production-ready. Please see the [audit report](audit_report.pdf) for the results of the audit. 14 | 15 | ### dependencies 16 | 17 | go 1.21 18 | 19 | ### usage 20 | 21 | Example: key generation, signing, and verification 22 | 23 | ```go 24 | package main 25 | 26 | import ( 27 | "fmt" 28 | 29 | "github.com/ChainSafe/go-schnorrkel" 30 | ) 31 | 32 | func main() { 33 | msg := []byte("hello friends") 34 | signingCtx := []byte("example") 35 | 36 | signingTranscript := schnorrkel.NewSigningContext(signingCtx, msg) 37 | verifyTranscript := schnorrkel.NewSigningContext(signingCtx, msg) 38 | 39 | priv, pub, err := schnorrkel.GenerateKeypair() 40 | if err != nil { 41 | panic(err) 42 | } 43 | 44 | sig, err := priv.Sign(signingTranscript) 45 | if err != nil { 46 | panic(err) 47 | } 48 | 49 | ok, err := pub.Verify(sig, verifyTranscript) 50 | if err != nil { 51 | panic(err) 52 | } 53 | if !ok { 54 | fmt.Println("failed to verify signature") 55 | return 56 | } 57 | 58 | fmt.Println("verified signature") 59 | } 60 | ``` 61 | 62 | Please see the [godocs](https://pkg.go.dev/github.com/ChainSafe/go-schnorrkel) for more usage examples. 63 | -------------------------------------------------------------------------------- /audit_report.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ChainSafe/go-schnorrkel/194103b33aa50bfe076cf3be3dc110d9d6b0a749/audit_report.pdf -------------------------------------------------------------------------------- /batch.go: -------------------------------------------------------------------------------- 1 | package schnorrkel 2 | 3 | import ( 4 | "errors" 5 | 6 | "github.com/gtank/merlin" 7 | r255 "github.com/gtank/ristretto255" 8 | ) 9 | 10 | // VerifyBatch batch verifies the given signatures 11 | func VerifyBatch(transcripts []*merlin.Transcript, signatures []*Signature, pubkeys []*PublicKey) (bool, error) { 12 | if len(transcripts) != len(signatures) || len(signatures) != len(pubkeys) || len(pubkeys) != len(transcripts) { 13 | return false, errors.New("the number of transcripts, signatures, and public keys must be equal") 14 | } 15 | 16 | if len(transcripts) == 0 { 17 | return true, nil 18 | } 19 | 20 | var err error 21 | zero := r255.NewElement().Zero() 22 | zs := make([]*r255.Scalar, len(transcripts)) 23 | for i := range zs { 24 | zs[i], err = NewRandomScalar() 25 | if err != nil { 26 | return false, err 27 | } 28 | } 29 | 30 | // compute H(R_i || P_i || m_i) 31 | hs := make([]*r255.Scalar, len(transcripts)) 32 | s := make([]r255.Scalar, len(transcripts)) 33 | for i, t := range transcripts { 34 | if t == nil { 35 | return false, errors.New("transcript provided was nil") 36 | } 37 | 38 | t.AppendMessage([]byte("proto-name"), []byte("Schnorr-sig")) 39 | pubc := pubkeys[i].Encode() 40 | t.AppendMessage([]byte("sign:pk"), pubc[:]) 41 | t.AppendMessage([]byte("sign:R"), signatures[i].r.Encode([]byte{})) 42 | 43 | h := t.ExtractBytes([]byte("sign:c"), 64) 44 | s[i] = *r255.NewScalar() 45 | hs[i] = &s[i] 46 | hs[i].FromUniformBytes(h) 47 | } 48 | 49 | // compute ∑ z_i P_i H(R_i || P_i || m_i) 50 | ps := make([]*r255.Element, len(pubkeys)) 51 | for i, p := range pubkeys { 52 | if p == nil { 53 | return false, errors.New("public key provided was nil") 54 | } 55 | 56 | ps[i] = r255.NewElement().ScalarMult(zs[i], p.key) 57 | } 58 | 59 | phs := r255.NewElement().VarTimeMultiScalarMult(hs, ps) 60 | 61 | // compute ∑ z_i s_i and ∑ z_i R_i 62 | ss := r255.NewScalar() 63 | rs := r255.NewElement() 64 | for i, s := range signatures { 65 | if s == nil { 66 | return false, errors.New("signature provided was nil") 67 | } 68 | 69 | zsi := r255.NewScalar().Multiply(s.s, zs[i]) 70 | ss = r255.NewScalar().Add(ss, zsi) 71 | zri := r255.NewElement().ScalarMult(zs[i], s.r) 72 | rs = r255.NewElement().Add(rs, zri) 73 | } 74 | 75 | // ∑ z_i P_i H(R_i || P_i || m_i) + ∑ R_i 76 | z := r255.NewElement().Add(phs, rs) 77 | 78 | // B ∑ z_i s_i 79 | sb := r255.NewElement().ScalarBaseMult(ss) 80 | 81 | // check -B ∑ z_i s_i + ∑ z_i P_i H(R_i || P_i || m_i) + ∑ z_i R_i = 0 82 | sb_neg := r255.NewElement().Negate(sb) 83 | res := r255.NewElement().Add(sb_neg, z) 84 | 85 | return res.Equal(zero) == 1, nil 86 | } 87 | 88 | type BatchVerifier struct { 89 | hs []*r255.Scalar // transcript scalar 90 | ss *r255.Scalar // sum of signature.S: ∑ z_i s_i 91 | rs *r255.Element // sum of signature.R: ∑ z_i R_i 92 | pubkeys []*r255.Element // z_i P_i 93 | } 94 | 95 | func NewBatchVerifier() *BatchVerifier { 96 | return &BatchVerifier{ 97 | hs: []*r255.Scalar{}, 98 | ss: r255.NewScalar(), 99 | rs: r255.NewElement(), 100 | pubkeys: []*r255.Element{}, 101 | } 102 | } 103 | 104 | func (v *BatchVerifier) Add(t *merlin.Transcript, sig *Signature, pubkey *PublicKey) error { 105 | if t == nil { 106 | return errors.New("provided transcript is nil") 107 | } 108 | 109 | if sig == nil { 110 | return errors.New("provided signature is nil") 111 | } 112 | 113 | if pubkey == nil { 114 | return errors.New("provided public key is nil") 115 | } 116 | 117 | z, err := NewRandomScalar() 118 | if err != nil { 119 | return err 120 | } 121 | 122 | t.AppendMessage([]byte("proto-name"), []byte("Schnorr-sig")) 123 | pubc := pubkey.Encode() 124 | t.AppendMessage([]byte("sign:pk"), pubc[:]) 125 | t.AppendMessage([]byte("sign:R"), sig.r.Encode([]byte{})) 126 | 127 | h := t.ExtractBytes([]byte("sign:c"), 64) 128 | s := r255.NewScalar() 129 | s.FromUniformBytes(h) 130 | v.hs = append(v.hs, s) 131 | 132 | zs := r255.NewScalar().Multiply(z, sig.s) 133 | v.ss.Add(v.ss, zs) 134 | zr := r255.NewElement().ScalarMult(z, sig.r) 135 | v.rs.Add(v.rs, zr) 136 | 137 | p := r255.NewElement().ScalarMult(z, pubkey.key) 138 | v.pubkeys = append(v.pubkeys, p) 139 | return nil 140 | } 141 | 142 | func (v *BatchVerifier) Verify() bool { 143 | zero := r255.NewElement().Zero() 144 | 145 | // compute ∑ z_i P_i H(R_i || P_i || m_i) 146 | phs := r255.NewElement().VarTimeMultiScalarMult(v.hs, v.pubkeys) 147 | 148 | // ∑ z_i P_i H(R_i || P_i || m_i) + ∑ z_i R_i 149 | z := r255.NewElement().Add(phs, v.rs) 150 | 151 | // B ∑ z_i s_i 152 | sb := r255.NewElement().ScalarBaseMult(v.ss) 153 | 154 | // check -B ∑ z_i s_i + ∑ z_i P_i H(R_i || P_i || m_i) + ∑ z_i R_i = 0 155 | sb_neg := r255.NewElement().Negate(sb) 156 | res := r255.NewElement().Add(sb_neg, z) 157 | 158 | return res.Equal(zero) == 1 159 | } 160 | -------------------------------------------------------------------------------- /batch_test.go: -------------------------------------------------------------------------------- 1 | package schnorrkel_test 2 | 3 | import ( 4 | "fmt" 5 | "testing" 6 | 7 | "github.com/ChainSafe/go-schnorrkel" 8 | 9 | "github.com/gtank/merlin" 10 | "github.com/stretchr/testify/require" 11 | ) 12 | 13 | func ExampleVerifyBatch() { 14 | num := 16 15 | transcripts := make([]*merlin.Transcript, num) 16 | sigs := make([]*schnorrkel.Signature, num) 17 | pubkeys := make([]*schnorrkel.PublicKey, num) 18 | 19 | for i := 0; i < num; i++ { 20 | transcript := merlin.NewTranscript(fmt.Sprintf("hello_%d", i)) 21 | priv, pub, err := schnorrkel.GenerateKeypair() 22 | if err != nil { 23 | panic(err) 24 | } 25 | 26 | sigs[i], err = priv.Sign(transcript) 27 | if err != nil { 28 | panic(err) 29 | } 30 | 31 | transcripts[i] = merlin.NewTranscript(fmt.Sprintf("hello_%d", i)) 32 | pubkeys[i] = pub 33 | } 34 | 35 | ok, err := schnorrkel.VerifyBatch(transcripts, sigs, pubkeys) 36 | if err != nil { 37 | panic(err) 38 | } 39 | 40 | if !ok { 41 | fmt.Println("failed to batch verify signatures") 42 | return 43 | } 44 | 45 | fmt.Println("batch verified signatures") 46 | // Output: batch verified signatures 47 | } 48 | 49 | func ExampleBatchVerifier() { 50 | num := 16 51 | v := schnorrkel.NewBatchVerifier() 52 | 53 | for i := 0; i < num; i++ { 54 | transcript := merlin.NewTranscript(fmt.Sprintf("hello_%d", i)) 55 | priv, pub, err := schnorrkel.GenerateKeypair() 56 | if err != nil { 57 | panic(err) 58 | } 59 | 60 | sig, err := priv.Sign(transcript) 61 | if err != nil { 62 | panic(err) 63 | } 64 | 65 | transcript = merlin.NewTranscript(fmt.Sprintf("hello_%d", i)) 66 | err = v.Add(transcript, sig, pub) 67 | if err != nil { 68 | panic(err) 69 | } 70 | } 71 | 72 | ok := v.Verify() 73 | if !ok { 74 | fmt.Println("failed to batch verify signatures") 75 | return 76 | } 77 | 78 | fmt.Println("batch verified signatures") 79 | // Output: batch verified signatures 80 | } 81 | 82 | func TestBatchVerify(t *testing.T) { 83 | num := 16 84 | transcripts := make([]*merlin.Transcript, num) 85 | sigs := make([]*schnorrkel.Signature, num) 86 | pubkeys := make([]*schnorrkel.PublicKey, num) 87 | 88 | for i := 0; i < num; i++ { 89 | transcript := merlin.NewTranscript(fmt.Sprintf("hello_%d", i)) 90 | priv, pub, err := schnorrkel.GenerateKeypair() 91 | require.NoError(t, err) 92 | 93 | sigs[i], err = priv.Sign(transcript) 94 | require.NoError(t, err) 95 | 96 | transcripts[i] = merlin.NewTranscript(fmt.Sprintf("hello_%d", i)) 97 | pubkeys[i] = pub 98 | } 99 | 100 | ok, err := schnorrkel.VerifyBatch(transcripts, sigs, pubkeys) 101 | require.NoError(t, err) 102 | require.True(t, ok) 103 | } 104 | 105 | func TestBatchVerify_Bad(t *testing.T) { 106 | num := 16 107 | transcripts := make([]*merlin.Transcript, num) 108 | sigs := make([]*schnorrkel.Signature, num) 109 | pubkeys := make([]*schnorrkel.PublicKey, num) 110 | 111 | for i := 0; i < num; i++ { 112 | transcript := merlin.NewTranscript(fmt.Sprintf("hello_%d", i)) 113 | priv, pub, err := schnorrkel.GenerateKeypair() 114 | require.NoError(t, err) 115 | 116 | sigs[i], err = priv.Sign(transcript) 117 | require.NoError(t, err) 118 | 119 | transcripts[i] = merlin.NewTranscript(fmt.Sprintf("hello_%d", i)) 120 | pubkeys[i] = pub 121 | } 122 | 123 | transcripts[6] = merlin.NewTranscript(fmt.Sprintf("hello_%d", 999)) 124 | ok, err := schnorrkel.VerifyBatch(transcripts, sigs, pubkeys) 125 | require.NoError(t, err) 126 | require.False(t, ok) 127 | } 128 | 129 | func TestBatchVerifier(t *testing.T) { 130 | num := 16 131 | v := schnorrkel.NewBatchVerifier() 132 | 133 | for i := 0; i < num; i++ { 134 | transcript := merlin.NewTranscript(fmt.Sprintf("hello_%d", i)) 135 | priv, pub, err := schnorrkel.GenerateKeypair() 136 | require.NoError(t, err) 137 | 138 | sig, err := priv.Sign(transcript) 139 | require.NoError(t, err) 140 | 141 | transcript = merlin.NewTranscript(fmt.Sprintf("hello_%d", i)) 142 | err = v.Add(transcript, sig, pub) 143 | require.NoError(t, err) 144 | } 145 | 146 | ok := v.Verify() 147 | require.True(t, ok) 148 | } 149 | -------------------------------------------------------------------------------- /bip39.go: -------------------------------------------------------------------------------- 1 | package schnorrkel 2 | 3 | import ( 4 | "crypto/sha512" 5 | "errors" 6 | "math/big" 7 | "strings" 8 | 9 | "github.com/cosmos/go-bip39" 10 | "golang.org/x/crypto/pbkdf2" 11 | ) 12 | 13 | // entropy mnemonic bit size 14 | const entropySize = 256 15 | 16 | // WARNING: Non-standard BIP39 Implementation 17 | // Designed for compatibility with the Rust substrate-bip39 library 18 | 19 | // GenerateMnemonic returns mnemonic for func MiniSecretKeyFromMnemonic 20 | func GenerateMnemonic() (string, error) { 21 | entropy, err := bip39.NewEntropy(entropySize) 22 | if err != nil { 23 | return "", err 24 | } 25 | 26 | mnemonic, err := bip39.NewMnemonic(entropy) 27 | if err != nil { 28 | return "", err 29 | } 30 | 31 | return mnemonic, nil 32 | } 33 | 34 | // MiniSecretKeyFromMnemonic returns a go-schnorrkel MiniSecretKey from a bip39 mnemonic 35 | func MiniSecretKeyFromMnemonic(mnemonic string, password string) (*MiniSecretKey, error) { 36 | seed, err := SeedFromMnemonic(mnemonic, password) 37 | if err != nil { 38 | return nil, err 39 | } 40 | var secret [32]byte 41 | copy(secret[:], seed[:32]) 42 | return NewMiniSecretKeyFromRaw(secret) 43 | } 44 | 45 | // SeedFromMnemonic returns a 64-byte seed from a bip39 mnemonic 46 | func SeedFromMnemonic(mnemonic string, password string) ([64]byte, error) { 47 | entropy, err := MnemonicToEntropy(mnemonic) 48 | if err != nil { 49 | return [64]byte{}, err 50 | } 51 | 52 | if len(entropy) < 16 || len(entropy) > 32 || len(entropy)%4 != 0 { 53 | return [64]byte{}, errors.New("invalid entropy") 54 | } 55 | 56 | bz := pbkdf2.Key(entropy, []byte("mnemonic"+password), 2048, 64, sha512.New) 57 | var bzArr [64]byte 58 | copy(bzArr[:], bz[:64]) 59 | 60 | return bzArr, nil 61 | } 62 | 63 | // MnemonicToEntropy takes a mnemonic string and reverses it to the entropy 64 | // An error is returned if the mnemonic is invalid. 65 | func MnemonicToEntropy(mnemonic string) ([]byte, error) { 66 | _, err := bip39.MnemonicToByteArray(mnemonic) 67 | if err != nil { 68 | return nil, err 69 | } 70 | 71 | mnemonicSlice := strings.Split(mnemonic, " ") 72 | bitSize := len(mnemonicSlice) * 11 73 | checksumSize := bitSize % 32 74 | b := big.NewInt(0) 75 | modulo := big.NewInt(2048) 76 | for _, v := range mnemonicSlice { 77 | index := bip39.ReverseWordMap[v] 78 | add := big.NewInt(int64(index)) 79 | b = b.Mul(b, modulo) 80 | b = b.Add(b, add) 81 | } 82 | checksumModulo := big.NewInt(0).Exp(big.NewInt(2), big.NewInt(int64(checksumSize)), nil) 83 | entropy, _ := big.NewInt(0).DivMod(b, checksumModulo, big.NewInt(0)) 84 | 85 | entropyHex := entropy.Bytes() 86 | 87 | // Add padding (no extra byte, entropy itself does not contain checksum) 88 | entropyByteSize := (bitSize - checksumSize) / 8 89 | if len(entropyHex) != entropyByteSize { 90 | tmp := make([]byte, entropyByteSize) 91 | diff := entropyByteSize - len(entropyHex) 92 | for i := 0; i < len(entropyHex); i++ { 93 | tmp[i+diff] = entropyHex[i] 94 | } 95 | entropyHex = tmp 96 | } 97 | 98 | return entropyHex, nil 99 | } 100 | -------------------------------------------------------------------------------- /bip39_test.go: -------------------------------------------------------------------------------- 1 | package schnorrkel_test 2 | 3 | import ( 4 | "encoding/hex" 5 | "testing" 6 | 7 | "github.com/ChainSafe/go-schnorrkel" 8 | 9 | "github.com/stretchr/testify/require" 10 | ) 11 | 12 | func TestSubstrateBip39(t *testing.T) { 13 | tests := []struct { 14 | mnemonic string 15 | hexEntropy string 16 | hexSeed string 17 | }{ 18 | { 19 | "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about", 20 | "00000000000000000000000000000000", 21 | "44e9d125f037ac1d51f0a7d3649689d422c2af8b1ec8e00d71db4d7bf6d127e33f50c3d5c84fa3e5399c72d6cbbbbc4a49bf76f76d952f479d74655a2ef2d453", 22 | }, 23 | { 24 | "legal winner thank year wave sausage worth useful legal winner thank yellow", 25 | "7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f", 26 | "4313249608fe8ac10fd5886c92c4579007272cb77c21551ee5b8d60b780416850f1e26c1f4b8d88ece681cb058ab66d6182bc2ce5a03181f7b74c27576b5c8bf", 27 | }, 28 | { 29 | "letter advice cage absurd amount doctor acoustic avoid letter advice cage above", 30 | "80808080808080808080808080808080", 31 | "27f3eb595928c60d5bc91a4d747da40ed236328183046892ed6cd5aa9ae38122acd1183adf09a89839acb1e6eaa7fb563cc958a3f9161248d5a036e0d0af533d", 32 | }, 33 | { 34 | "zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo wrong", 35 | "ffffffffffffffffffffffffffffffff", 36 | "227d6256fd4f9ccaf06c45eaa4b2345969640462bbb00c5f51f43cb43418c7a753265f9b1e0c0822c155a9cabc769413ecc14553e135fe140fc50b6722c6b9df", 37 | }, 38 | { 39 | "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon agent", 40 | "000000000000000000000000000000000000000000000000", 41 | "44e9d125f037ac1d51f0a7d3649689d422c2af8b1ec8e00d71db4d7bf6d127e33f50c3d5c84fa3e5399c72d6cbbbbc4a49bf76f76d952f479d74655a2ef2d453", 42 | }, 43 | { 44 | "legal winner thank year wave sausage worth useful legal winner thank year wave sausage worth useful legal will", 45 | "7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f", 46 | "cb1d50e14101024a88905a098feb1553d4306d072d7460e167a60ccb3439a6817a0afc59060f45d999ddebc05308714733c9e1e84f30feccddd4ad6f95c8a445", 47 | }, 48 | { 49 | "letter advice cage absurd amount doctor acoustic avoid letter advice cage absurd amount doctor acoustic avoid letter always", 50 | "808080808080808080808080808080808080808080808080", 51 | "9ddecf32ce6bee77f867f3c4bb842d1f0151826a145cb4489598fe71ac29e3551b724f01052d1bc3f6d9514d6df6aa6d0291cfdf997a5afdb7b6a614c88ab36a", 52 | }, 53 | { 54 | "zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo when", 55 | "ffffffffffffffffffffffffffffffffffffffffffffffff", 56 | "8971cb290e7117c64b63379c97ed3b5c6da488841bd9f95cdc2a5651ac89571e2c64d391d46e2475e8b043911885457cd23e99a28b5a18535fe53294dc8e1693", 57 | }, 58 | { 59 | "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon art", 60 | "0000000000000000000000000000000000000000000000000000000000000000", 61 | "44e9d125f037ac1d51f0a7d3649689d422c2af8b1ec8e00d71db4d7bf6d127e33f50c3d5c84fa3e5399c72d6cbbbbc4a49bf76f76d952f479d74655a2ef2d453", 62 | }, 63 | { 64 | "legal winner thank year wave sausage worth useful legal winner thank year wave sausage worth useful legal winner thank year wave sausage worth title", 65 | "7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f", 66 | "3037276a5d05fcd7edf51869eb841bdde27c574dae01ac8cfb1ea476f6bea6ef57ab9afe14aea1df8a48f97ae25b37d7c8326e49289efb25af92ba5a25d09ed3", 67 | }, 68 | { 69 | "letter advice cage absurd amount doctor acoustic avoid letter advice cage absurd amount doctor acoustic avoid letter advice cage absurd amount doctor acoustic bless", 70 | "8080808080808080808080808080808080808080808080808080808080808080", 71 | "2c9c6144a06ae5a855453d98c3dea470e2a8ffb78179c2e9eb15208ccca7d831c97ddafe844ab933131e6eb895f675ede2f4e39837bb5769d4e2bc11df58ac42", 72 | }, 73 | { 74 | "zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo vote", 75 | "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", 76 | "047e89ef7739cbfe30da0ad32eb1720d8f62441dd4f139b981b8e2d0bd412ed4eb14b89b5098c49db2301d4e7df4e89c21e53f345138e56a5e7d63fae21c5939", 77 | }, 78 | { 79 | "ozone drill grab fiber curtain grace pudding thank cruise elder eight picnic", 80 | "9e885d952ad362caeb4efe34a8e91bd2", 81 | "f4956be6960bc145cdab782e649a5056598fd07cd3f32ceb73421c3da27833241324dc2c8b0a4d847eee457e6d4c5429f5e625ece22abaa6a976e82f1ec5531d", 82 | }, 83 | { 84 | "gravity machine north sort system female filter attitude volume fold club stay feature office ecology stable narrow fog", 85 | "6610b25967cdcca9d59875f5cb50b0ea75433311869e930b", 86 | "fbcc5229ade0c0ff018cb7a329c5459f91876e4dde2a97ddf03c832eab7f26124366a543f1485479c31a9db0d421bda82d7e1fe562e57f3533cb1733b001d84d", 87 | }, 88 | { 89 | "hamster diagram private dutch cause delay private meat slide toddler razor book happy fancy gospel tennis maple dilemma loan word shrug inflict delay length", 90 | "68a79eaca2324873eacc50cb9c6eca8cc68ea5d936f98787c60c7ebc74e6ce7c", 91 | "7c60c555126c297deddddd59f8cdcdc9e3608944455824dd604897984b5cc369cad749803bb36eb8b786b570c9cdc8db275dbe841486676a6adf389f3be3f076", 92 | }, 93 | { 94 | "scheme spot photo card baby mountain device kick cradle pact join borrow", 95 | "c0ba5a8e914111210f2bd131f3d5e08d", 96 | "c12157bf2506526c4bd1b79a056453b071361538e9e2c19c28ba2cfa39b5f23034b974e0164a1e8acd30f5b4c4de7d424fdb52c0116bfc6a965ba8205e6cc121", 97 | }, 98 | { 99 | "horn tenant knee talent sponsor spell gate clip pulse soap slush warm silver nephew swap uncle crack brave", 100 | "6d9be1ee6ebd27a258115aad99b7317b9c8d28b6d76431c3", 101 | "23766723e970e6b79dec4d5e4fdd627fd27d1ee026eb898feb9f653af01ad22080c6f306d1061656d01c4fe9a14c05f991d2c7d8af8730780de4f94cd99bd819", 102 | }, 103 | { 104 | "panda eyebrow bullet gorilla call smoke muffin taste mesh discover soft ostrich alcohol speed nation flash devote level hobby quick inner drive ghost inside", 105 | "9f6a2878b2520799a44ef18bc7df394e7061a224d2c33cd015b157d746869863", 106 | "f4c83c86617cb014d35cd87d38b5ef1c5d5c3d58a73ab779114438a7b358f457e0462c92bddab5a406fe0e6b97c71905cf19f925f356bc673ceb0e49792f4340", 107 | }, 108 | { 109 | "cat swing flag economy stadium alone churn speed unique patch report train", 110 | "23db8160a31d3e0dca3688ed941adbf3", 111 | "719d4d4de0638a1705bf5237262458983da76933e718b2d64eb592c470f3c5d222e345cc795337bb3da393b94375ff4a56cfcd68d5ea25b577ee9384d35f4246", 112 | }, 113 | { 114 | "light rule cinnamon wrap drastic word pride squirrel upgrade then income fatal apart sustain crack supply proud access", 115 | "8197a4a47f0425faeaa69deebc05ca29c0a5b5cc76ceacc0", 116 | "7ae1291db32d16457c248567f2b101e62c5549d2a64cd2b7605d503ec876d58707a8d663641e99663bc4f6cc9746f4852e75e7e54de5bc1bd3c299c9a113409e", 117 | }, 118 | { 119 | "all hour make first leader extend hole alien behind guard gospel lava path output census museum junior mass reopen famous sing advance salt reform", 120 | "066dca1a2bb7e8a1db2832148ce9933eea0f3ac9548d793112d9a95c9407efad", 121 | "a911a5f4db0940b17ecb79c4dcf9392bf47dd18acaebdd4ef48799909ebb49672947cc15f4ef7e8ef47103a1a91a6732b821bda2c667e5b1d491c54788c69391", 122 | }, 123 | { 124 | "vessel ladder alter error federal sibling chat ability sun glass valve picture", 125 | "f30f8c1da665478f49b001d94c5fc452", 126 | "4e2314ca7d9eebac6fe5a05a5a8d3546bc891785414d82207ac987926380411e559c885190d641ff7e686ace8c57db6f6e4333c1081e3d88d7141a74cf339c8f", 127 | }, 128 | { 129 | "scissors invite lock maple supreme raw rapid void congress muscle digital elegant little brisk hair mango congress clump", 130 | "c10ec20dc3cd9f652c7fac2f1230f7a3c828389a14392f05", 131 | "7a83851102849edc5d2a3ca9d8044d0d4f00e5c4a292753ed3952e40808593251b0af1dd3c9ed9932d46e8608eb0b928216a6160bd4fc775a6e6fbd493d7c6b2", 132 | }, 133 | { 134 | "void come effort suffer camp survey warrior heavy shoot primary clutch crush open amazing screen patrol group space point ten exist slush involve unfold", 135 | "f585c11aec520db57dd353c69554b21a89b20fb0650966fa0a9d6f74fd989d8f", 136 | "938ba18c3f521f19bd4a399c8425b02c716844325b1a65106b9d1593fbafe5e0b85448f523f91c48e331995ff24ae406757cff47d11f240847352b348ff436ed", 137 | }, 138 | } 139 | for _, tc := range tests { 140 | entropy, err := schnorrkel.MnemonicToEntropy(tc.mnemonic) 141 | require.NoError(t, err) 142 | seed, err := schnorrkel.SeedFromMnemonic(tc.mnemonic, "Substrate") 143 | require.NoError(t, err) 144 | miniSecret, err := schnorrkel.MiniSecretKeyFromMnemonic(tc.mnemonic, "Substrate") 145 | require.NoError(t, err) 146 | miniSecretBytes := miniSecret.Encode() 147 | 148 | require.Equal(t, tc.hexEntropy, hex.EncodeToString(entropy)) 149 | require.Equal(t, tc.hexSeed, hex.EncodeToString(seed[:])) 150 | require.Equal(t, tc.hexSeed[:64], hex.EncodeToString(miniSecretBytes[:])) 151 | } 152 | } 153 | -------------------------------------------------------------------------------- /derive.go: -------------------------------------------------------------------------------- 1 | package schnorrkel 2 | 3 | import ( 4 | "crypto/rand" 5 | "errors" 6 | 7 | "github.com/gtank/merlin" 8 | r255 "github.com/gtank/ristretto255" 9 | ) 10 | 11 | const ChainCodeLength = 32 12 | 13 | var ( 14 | ErrDeriveHardKeyType = errors.New("cannot derive hard key type, DerivableKey must be of type SecretKey") 15 | ) 16 | 17 | // DerivableKey implements DeriveKey 18 | type DerivableKey interface { 19 | Encode() [32]byte 20 | Decode([32]byte) error 21 | DeriveKey(*merlin.Transcript, [ChainCodeLength]byte) (*ExtendedKey, error) 22 | } 23 | 24 | // ExtendedKey consists of a DerivableKey which can be a schnorrkel public or private key 25 | // as well as chain code 26 | type ExtendedKey struct { 27 | key DerivableKey 28 | chaincode [ChainCodeLength]byte 29 | } 30 | 31 | // NewExtendedKey creates an ExtendedKey given a DerivableKey and chain code 32 | func NewExtendedKey(k DerivableKey, cc [ChainCodeLength]byte) *ExtendedKey { 33 | return &ExtendedKey{ 34 | key: k, 35 | chaincode: cc, 36 | } 37 | } 38 | 39 | // Key returns the schnorrkel key underlying the ExtendedKey 40 | func (ek *ExtendedKey) Key() DerivableKey { 41 | return ek.key 42 | } 43 | 44 | // ChainCode returns the chain code underlying the ExtendedKey 45 | func (ek *ExtendedKey) ChainCode() [ChainCodeLength]byte { 46 | return ek.chaincode 47 | } 48 | 49 | // Secret returns the SecretKey underlying the ExtendedKey 50 | // if it's not a secret key, it returns an error 51 | func (ek *ExtendedKey) Secret() (*SecretKey, error) { 52 | if priv, ok := ek.key.(*SecretKey); ok { 53 | return priv, nil 54 | } 55 | 56 | return nil, errors.New("extended key is not a secret key") 57 | } 58 | 59 | // Public returns the PublicKey underlying the ExtendedKey 60 | func (ek *ExtendedKey) Public() (*PublicKey, error) { 61 | if pub, ok := ek.key.(*PublicKey); ok { 62 | return pub, nil 63 | } 64 | 65 | if priv, ok := ek.key.(*SecretKey); ok { 66 | return priv.Public() 67 | } 68 | 69 | return nil, errors.New("extended key is not a valid public or private key") 70 | } 71 | 72 | // DeriveKey derives an extended key from an extended key 73 | func (ek *ExtendedKey) DeriveKey(t *merlin.Transcript) (*ExtendedKey, error) { 74 | return ek.key.DeriveKey(t, ek.chaincode) 75 | } 76 | 77 | // HardDeriveMiniSecretKey implements BIP-32 like "hard" derivation of a mini 78 | // secret from an extended key's secret key 79 | func (ek *ExtendedKey) HardDeriveMiniSecretKey(i []byte) (*ExtendedKey, error) { 80 | sk, err := ek.Secret() 81 | if err != nil { 82 | return nil, err 83 | } 84 | 85 | msk, chainCode, err := sk.HardDeriveMiniSecretKey(i, ek.chaincode) 86 | if err != nil { 87 | return nil, err 88 | } 89 | 90 | return NewExtendedKey(msk, chainCode), nil 91 | } 92 | 93 | // DeriveKeyHard derives a Hard subkey identified by the byte array i and chain 94 | // code 95 | func DeriveKeyHard(key DerivableKey, i []byte, cc [ChainCodeLength]byte) (*ExtendedKey, error) { 96 | switch k := key.(type) { 97 | case *SecretKey: 98 | msk, resCC, err := k.HardDeriveMiniSecretKey(i, cc) 99 | if err != nil { 100 | return nil, err 101 | } 102 | return NewExtendedKey(msk.ExpandEd25519(), resCC), nil 103 | 104 | default: 105 | return nil, ErrDeriveHardKeyType 106 | } 107 | } 108 | 109 | // DerviveKeySoft is an alias for DervieKeySimple() used to derive a Soft subkey 110 | // identified by the byte array i and chain code 111 | func DeriveKeySoft(key DerivableKey, i []byte, cc [ChainCodeLength]byte) (*ExtendedKey, error) { 112 | return DeriveKeySimple(key, i, cc) 113 | } 114 | 115 | // DeriveKeySimple derives a Soft subkey identified by byte array i and chain code. 116 | func DeriveKeySimple(key DerivableKey, i []byte, cc [ChainCodeLength]byte) (*ExtendedKey, error) { 117 | t := merlin.NewTranscript("SchnorrRistrettoHDKD") 118 | t.AppendMessage([]byte("sign-bytes"), i) 119 | return key.DeriveKey(t, cc) 120 | } 121 | 122 | // DeriveKey derives a new secret key and chain code from an existing secret key and chain code 123 | func (secretKey *SecretKey) DeriveKey(t *merlin.Transcript, cc [ChainCodeLength]byte) (*ExtendedKey, error) { 124 | pub, err := secretKey.Public() 125 | if err != nil { 126 | return nil, err 127 | } 128 | 129 | sc, dcc, err := pub.DeriveScalarAndChaincode(t, cc) 130 | if err != nil { 131 | return nil, err 132 | } 133 | 134 | // TODO: need transcript RNG to match rust-schnorrkel 135 | // see: https://github.com/w3f/schnorrkel/blob/798ab3e0813aa478b520c5cf6dc6e02fd4e07f0a/src/derive.rs#L186 136 | nonce := [32]byte{} 137 | _, err = rand.Read(nonce[:]) 138 | if err != nil { 139 | return nil, err 140 | } 141 | 142 | dsk, err := ScalarFromBytes(secretKey.key) 143 | if err != nil { 144 | return nil, err 145 | } 146 | 147 | dsk.Add(dsk, sc) 148 | 149 | dskBytes := [32]byte{} 150 | copy(dskBytes[:], dsk.Encode([]byte{})) 151 | 152 | skNew := &SecretKey{ 153 | key: dskBytes, 154 | nonce: nonce, 155 | } 156 | 157 | return &ExtendedKey{ 158 | key: skNew, 159 | chaincode: dcc, 160 | }, nil 161 | } 162 | 163 | // HardDeriveMiniSecretKey implements BIP-32 like "hard" derivation of a mini 164 | // secret from a secret key 165 | func (secretKey *SecretKey) HardDeriveMiniSecretKey(i []byte, cc [ChainCodeLength]byte) ( 166 | *MiniSecretKey, [ChainCodeLength]byte, error) { 167 | t := merlin.NewTranscript("SchnorrRistrettoHDKD") 168 | t.AppendMessage([]byte("sign-bytes"), i) 169 | t.AppendMessage([]byte("chain-code"), cc[:]) 170 | skenc := secretKey.Encode() 171 | t.AppendMessage([]byte("secret-key"), skenc[:]) 172 | 173 | msk := [MiniSecretKeySize]byte{} 174 | mskBytes := t.ExtractBytes([]byte("HDKD-hard"), MiniSecretKeySize) 175 | copy(msk[:], mskBytes) 176 | 177 | ccRes := [ChainCodeLength]byte{} 178 | ccBytes := t.ExtractBytes([]byte("HDKD-chaincode"), ChainCodeLength) 179 | copy(ccRes[:], ccBytes) 180 | 181 | miniSec, err := NewMiniSecretKeyFromRaw(msk) 182 | 183 | return miniSec, ccRes, err 184 | } 185 | 186 | // HardDeriveMiniSecretKey implements BIP-32 like "hard" derivation of a mini 187 | // secret from a mini secret key 188 | func (miniSecretKey *MiniSecretKey) HardDeriveMiniSecretKey(i []byte, cc [ChainCodeLength]byte) ( 189 | *MiniSecretKey, [ChainCodeLength]byte, error) { 190 | sk := miniSecretKey.ExpandEd25519() 191 | return sk.HardDeriveMiniSecretKey(i, cc) 192 | } 193 | 194 | // DeriveKey derives an Extended Key from the Mini Secret Key 195 | func (miniSecretKey *MiniSecretKey) DeriveKey(t *merlin.Transcript, cc [ChainCodeLength]byte) (*ExtendedKey, error) { 196 | if t == nil { 197 | return nil, errors.New("transcript provided is nil") 198 | } 199 | 200 | sk := miniSecretKey.ExpandEd25519() 201 | return sk.DeriveKey(t, cc) 202 | } 203 | 204 | func (publicKey *PublicKey) DeriveKey(t *merlin.Transcript, cc [ChainCodeLength]byte) (*ExtendedKey, error) { 205 | if t == nil { 206 | return nil, errors.New("transcript provided is nil") 207 | } 208 | 209 | sc, dcc, err := publicKey.DeriveScalarAndChaincode(t, cc) 210 | if err != nil { 211 | return nil, err 212 | } 213 | 214 | // derivedPk = pk + (sc * g) 215 | p1 := r255.NewElement().ScalarBaseMult(sc) 216 | p2 := r255.NewElement() 217 | p2.Add(publicKey.key, p1) 218 | 219 | pub := &PublicKey{ 220 | key: p2, 221 | } 222 | 223 | return &ExtendedKey{ 224 | key: pub, 225 | chaincode: dcc, 226 | }, nil 227 | } 228 | 229 | // DeriveScalarAndChaincode derives a new scalar and chain code from an existing public key and chain code 230 | func (publicKey *PublicKey) DeriveScalarAndChaincode(t *merlin.Transcript, cc [ChainCodeLength]byte) (*r255.Scalar, [ChainCodeLength]byte, error) { 231 | if t == nil { 232 | return nil, [ChainCodeLength]byte{}, errors.New("transcript provided is nil") 233 | } 234 | 235 | t.AppendMessage([]byte("chain-code"), cc[:]) 236 | pkenc := publicKey.Encode() 237 | t.AppendMessage([]byte("public-key"), pkenc[:]) 238 | 239 | scBytes := t.ExtractBytes([]byte("HDKD-scalar"), 64) 240 | sc := r255.NewScalar() 241 | sc.FromUniformBytes(scBytes) 242 | 243 | ccBytes := t.ExtractBytes([]byte("HDKD-chaincode"), ChainCodeLength) 244 | ccRes := [ChainCodeLength]byte{} 245 | copy(ccRes[:], ccBytes) 246 | return sc, ccRes, nil 247 | } 248 | -------------------------------------------------------------------------------- /derive_test.go: -------------------------------------------------------------------------------- 1 | package schnorrkel 2 | 3 | import ( 4 | "encoding/hex" 5 | "testing" 6 | 7 | "github.com/stretchr/testify/require" 8 | "golang.org/x/crypto/blake2b" 9 | ) 10 | 11 | func TestDeriveKey(t *testing.T) { 12 | priv, _, err := GenerateKeypair() 13 | require.NoError(t, err) 14 | 15 | transcript := NewSigningContext([]byte("test"), []byte("noot")) 16 | msg := []byte("hello") 17 | cc := blake2b.Sum256(msg) 18 | _, err = priv.DeriveKey(transcript, cc) 19 | require.NoError(t, err) 20 | } 21 | 22 | func TestDerivePublicAndPrivateMatch(t *testing.T) { 23 | priv, pub, err := GenerateKeypair() 24 | require.NoError(t, err) 25 | 26 | transcriptPriv := NewSigningContext([]byte("test"), []byte("noot")) 27 | transcriptPub := NewSigningContext([]byte("test"), []byte("noot")) 28 | msg := []byte("hello") 29 | cc := blake2b.Sum256(msg) 30 | 31 | dpriv, err := priv.DeriveKey(transcriptPriv, cc) 32 | require.NoError(t, err) 33 | 34 | // confirm chain codes are the same for private and public paths 35 | dpub, _ := pub.DeriveKey(transcriptPub, cc) 36 | require.Equal(t, dpriv.chaincode, dpub.chaincode) 37 | 38 | dpub2, err := dpriv.key.(*SecretKey).Public() 39 | require.NoError(t, err) 40 | 41 | pubbytes := dpub.key.Encode() 42 | pubFromPrivBytes := dpub2.Encode() 43 | 44 | // confirm public keys are the same from private and public paths 45 | require.Equal(t, pubbytes, pubFromPrivBytes) 46 | 47 | signingTranscript := NewSigningContext([]byte("test"), []byte("signme")) 48 | verifyTranscript := NewSigningContext([]byte("test"), []byte("signme")) 49 | sig, err := dpriv.key.(*SecretKey).Sign(signingTranscript) 50 | require.NoError(t, err) 51 | 52 | // confirm that key derived from public path can verify signature derived from private path 53 | ok, err := dpub.key.(*PublicKey).Verify(sig, verifyTranscript) 54 | require.NoError(t, err) 55 | require.True(t, ok) 56 | } 57 | 58 | func TestDeriveSoft(t *testing.T) { 59 | // test vectors from https://github.com/Warchant/sr25519-crust/blob/master/test/derive.cpp#L32 60 | c := commonVectors{ 61 | KeyPair: "4c1250e05afcd79e74f6c035aee10248841090e009b6fd7ba6a98d5dc743250cafa4b32c608e3ee2ba624850b3f14c75841af84b16798bf1ee4a3875aa37a2cee661e416406384fe1ca091980958576d2bff7c461636e9f22c895f444905ea1f", 62 | ChainCode: "0c666f6f00000000000000000000000000000000000000000000000000000000", 63 | Public: "b21e5aabeeb35d6a1bf76226a6c65cd897016df09ef208243e59eed2401f5357", 64 | Hard: false, 65 | } 66 | 67 | deriveCommon(t, c) 68 | } 69 | 70 | func TestDeriveHard(t *testing.T) { 71 | // test vectors from https://github.com/Warchant/sr25519-crust/blob/4b167a8db2c4114561e5380e3493375df426b124/test/derive.cpp#L13 72 | c := commonVectors{ 73 | KeyPair: "4c1250e05afcd79e74f6c035aee10248841090e009b6fd7ba6a98d5dc743250cafa4b32c608e3ee2ba624850b3f14c75841af84b16798bf1ee4a3875aa37a2cee661e416406384fe1ca091980958576d2bff7c461636e9f22c895f444905ea1f", 74 | ChainCode: "14416c6963650000000000000000000000000000000000000000000000000000", 75 | Public: "d8db757f04521a940f0237c8a1e44dfbe0b3e39af929eb2e9e257ba61b9a0a1a", 76 | Hard: true, 77 | } 78 | 79 | deriveCommon(t, c) 80 | } 81 | 82 | // commonVectors is a struct to set the vectors used for deriving soft or hard 83 | // keys for testing 84 | type commonVectors struct { 85 | // KeyPair in the hex encoded string of a known keypair 86 | KeyPair string 87 | // ChainCode is the chain code for generating the derived key hex encoded 88 | ChainCode string 89 | // Public is the expected resulting public key of the derived key hex 90 | // encoded 91 | Public string 92 | // Hard indicates if the vectors are for deriving a Hard key 93 | Hard bool 94 | } 95 | 96 | // deriveCommon provides common functions for testing Soft and Hard key derivation 97 | func deriveCommon(t *testing.T, vec commonVectors) { 98 | kp, err := hex.DecodeString(vec.KeyPair) 99 | require.NoError(t, err) 100 | 101 | cc, err := hex.DecodeString(vec.ChainCode) 102 | require.NoError(t, err) 103 | 104 | privBytes := [32]byte{} 105 | copy(privBytes[:], kp[:32]) 106 | priv := new(SecretKey) 107 | err = priv.Decode(privBytes) 108 | require.NoError(t, err) 109 | 110 | ccBytes := [32]byte{} 111 | copy(ccBytes[:], cc) 112 | 113 | var derived *ExtendedKey 114 | 115 | if vec.Hard { 116 | derived, err = DeriveKeyHard(priv, []byte{}, ccBytes) 117 | } else { 118 | derived, err = DeriveKeySimple(priv, []byte{}, ccBytes) 119 | } 120 | require.NoError(t, err) 121 | 122 | expectedPub, err := hex.DecodeString(vec.Public) 123 | require.NoError(t, err) 124 | 125 | resultPub, err := derived.Public() 126 | require.NoError(t, err) 127 | 128 | resultPubBytes := resultPub.Encode() 129 | require.Equal(t, expectedPub, resultPubBytes[:]) 130 | } 131 | -------------------------------------------------------------------------------- /example_test.go: -------------------------------------------------------------------------------- 1 | package schnorrkel_test 2 | 3 | import ( 4 | "fmt" 5 | 6 | "github.com/ChainSafe/go-schnorrkel" 7 | "github.com/gtank/merlin" 8 | ) 9 | 10 | func ExampleMiniSecretKey() { 11 | // To create a private-public keypair from a subkey keypair, use `NewMiniSecretKeyFromRaw` 12 | // This example uses the substrate built-in key Alice: 13 | // $ subkey inspect //Alice 14 | priv, err := schnorrkel.NewMiniSecretKeyFromHex("0xe5be9a5092b81bca64be81d212e7f2f9eba183bb7a90954f7b76361f6edb5c0a") 15 | if err != nil { 16 | panic(err) 17 | } 18 | 19 | pub := priv.Public() 20 | fmt.Printf("0x%x", pub.Encode()) 21 | // Output: 0xd43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d 22 | } 23 | 24 | func ExampleMiniSecretKey_ExpandEd25519() { 25 | msg := []byte("hello") 26 | signingCtx := []byte("example") 27 | 28 | signingTranscript := schnorrkel.NewSigningContext(signingCtx, msg) 29 | 30 | msk, err := schnorrkel.NewMiniSecretKeyFromHex("0xe5be9a5092b81bca64be81d212e7f2f9eba183bb7a90954f7b76361f6edb5c0a") 31 | if err != nil { 32 | panic(err) 33 | } 34 | 35 | sk := msk.ExpandEd25519() 36 | 37 | _, err = sk.Sign(signingTranscript) 38 | if err != nil { 39 | panic(err) 40 | } 41 | 42 | fmt.Println("expanded private key") 43 | // Output: expanded private key 44 | } 45 | 46 | func ExampleGenerateKeypair() { 47 | priv, pub, err := schnorrkel.GenerateKeypair() 48 | if err != nil { 49 | panic(err) 50 | } 51 | 52 | privStr := fmt.Sprintf("0x%x", priv.Encode()) 53 | pubStr := fmt.Sprintf("0x%x", pub.Encode()) 54 | _, err = schnorrkel.NewMiniSecretKeyFromHex(privStr) 55 | if err != nil { 56 | fmt.Printf("failed to decode private key, %v\n", err) 57 | return 58 | } 59 | _, err = schnorrkel.NewPublicKeyFromHex(pubStr) 60 | if err != nil { 61 | fmt.Printf("failed to decode public key, %v\n", err) 62 | return 63 | } 64 | fmt.Println("example keypair") 65 | // Output: example keypair 66 | } 67 | 68 | func ExampleSignature() { 69 | msg := []byte("hello") 70 | signingCtx := []byte("example") 71 | 72 | signingTranscript := schnorrkel.NewSigningContext(signingCtx, msg) 73 | 74 | sk, _, err := schnorrkel.GenerateKeypair() 75 | if err != nil { 76 | panic(err) 77 | } 78 | 79 | sig, err := sk.Sign(signingTranscript) 80 | if err != nil { 81 | panic(err) 82 | } 83 | 84 | encoded := fmt.Sprintf("0x%x", sig.Encode()) 85 | 86 | _, err = schnorrkel.NewSignatureFromHex(encoded) 87 | if err != nil { 88 | fmt.Println("failed to decode signature") 89 | return 90 | } 91 | fmt.Println("example signature") 92 | // Output: example signature 93 | } 94 | 95 | func ExampleSecretKey_VrfSign() { 96 | priv, pub, err := schnorrkel.GenerateKeypair() 97 | if err != nil { 98 | panic(err) 99 | } 100 | 101 | signTranscript := merlin.NewTranscript("vrf-test") 102 | verifyTranscript := merlin.NewTranscript("vrf-test") 103 | 104 | inout, proof, err := priv.VrfSign(signTranscript) 105 | if err != nil { 106 | panic(err) 107 | } 108 | 109 | ok, err := pub.VrfVerify(verifyTranscript, inout.Output(), proof) 110 | if err != nil { 111 | panic(err) 112 | } 113 | 114 | if !ok { 115 | fmt.Println("failed to verify VRF output and proof") 116 | return 117 | } 118 | 119 | fmt.Println("verified VRF output and proof") 120 | // Output: verified VRF output and proof 121 | } 122 | 123 | func ExampleKeypair_VrfSign() { 124 | priv, pub, err := schnorrkel.GenerateKeypair() 125 | if err != nil { 126 | panic(err) 127 | } 128 | 129 | kp := schnorrkel.NewKeypair(pub, priv) 130 | 131 | signTranscript := merlin.NewTranscript("vrf-test") 132 | verifyTranscript := merlin.NewTranscript("vrf-test") 133 | 134 | inout, proof, err := kp.VrfSign(signTranscript) 135 | if err != nil { 136 | panic(err) 137 | } 138 | 139 | ok, err := kp.VrfVerify(verifyTranscript, inout.Output(), proof) 140 | if err != nil { 141 | panic(err) 142 | } 143 | 144 | if !ok { 145 | fmt.Println("failed to verify VRF output and proof") 146 | return 147 | } 148 | 149 | fmt.Println("verified VRF output and proof") 150 | // Output: verified VRF output and proof 151 | } 152 | 153 | func ExampleSecretKey_Sign() { 154 | msg := []byte("hello") 155 | signingCtx := []byte("example") 156 | 157 | signingTranscript := schnorrkel.NewSigningContext(signingCtx, msg) 158 | verifyTranscript := schnorrkel.NewSigningContext(signingCtx, msg) 159 | 160 | priv, pub, err := schnorrkel.GenerateKeypair() 161 | if err != nil { 162 | panic(err) 163 | } 164 | 165 | sig, err := priv.Sign(signingTranscript) 166 | if err != nil { 167 | panic(err) 168 | } 169 | 170 | ok, err := pub.Verify(sig, verifyTranscript) 171 | if err != nil { 172 | panic(err) 173 | } 174 | 175 | if !ok { 176 | fmt.Println("failed to verify signature") 177 | return 178 | } 179 | 180 | fmt.Println("verified signature") 181 | // Output: verified signature 182 | } 183 | 184 | func ExamplePublicKey_Verify() { 185 | signingContext := []byte("substrate") 186 | 187 | pub, err := schnorrkel.NewPublicKeyFromHex("0x46ebddef8cd9bb167dc30878d7113b7e168e6f0646beffd77d69d39bad76b47a") 188 | if err != nil { 189 | panic(err) 190 | } 191 | 192 | sig, err := schnorrkel.NewSignatureFromHex( 193 | "0x4e172314444b8f820bb54c22e95076f220ed25373e5c178234aa6c211d29271244b947e3ff3418ff6b45fd1df1140c8cbff69fc58ee6dc96df70936a2bb74b82") 194 | if err != nil { 195 | panic(err) 196 | } 197 | 198 | msg := []byte("this is a message") 199 | transcript := schnorrkel.NewSigningContext(signingContext, msg) 200 | ok, err := pub.Verify(sig, transcript) 201 | if err != nil { 202 | panic(err) 203 | } 204 | 205 | if !ok { 206 | fmt.Println("failed to verify signature") 207 | return 208 | } 209 | 210 | fmt.Println("verified signature") 211 | // Output: verified signature 212 | } 213 | 214 | func ExampleGenerateMnemonic() { 215 | mnemonic, err := schnorrkel.GenerateMnemonic() 216 | if err != nil { 217 | panic(err) 218 | } 219 | 220 | _, err = schnorrkel.MiniSecretKeyFromMnemonic(mnemonic, "") 221 | if err != nil { 222 | panic(err) 223 | } 224 | 225 | fmt.Println("generated mnemonic") 226 | // Output: generated mnemonic 227 | } 228 | 229 | func ExampleMiniSecretKeyFromMnemonic() { 230 | mnemonic := "legal winner thank year wave sausage worth useful legal winner thank yellow" 231 | msk, err := schnorrkel.MiniSecretKeyFromMnemonic(mnemonic, "Substrate") 232 | if err != nil { 233 | panic(err) 234 | } 235 | 236 | fmt.Printf("0x%x", msk.Encode()) 237 | // Output: 0x4313249608fe8ac10fd5886c92c4579007272cb77c21551ee5b8d60b78041685 238 | } 239 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/ChainSafe/go-schnorrkel 2 | 3 | go 1.21 4 | 5 | require ( 6 | github.com/cosmos/go-bip39 v1.0.0 7 | github.com/gtank/merlin v0.1.1 8 | github.com/gtank/ristretto255 v0.1.2 9 | github.com/stretchr/testify v1.9.0 10 | golang.org/x/crypto v0.29.0 11 | ) 12 | 13 | require ( 14 | github.com/davecgh/go-spew v1.1.1 // indirect 15 | github.com/mimoo/StrobeGo v0.0.0-20220103164710-9a04d6ca976b // indirect 16 | github.com/pmezard/go-difflib v1.0.0 // indirect 17 | golang.org/x/sys v0.27.0 // indirect 18 | gopkg.in/yaml.v3 v3.0.1 // indirect 19 | ) 20 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/cosmos/go-bip39 v1.0.0 h1:pcomnQdrdH22njcAatO0yWojsUnCO3y2tNoV1cb6hHY= 2 | github.com/cosmos/go-bip39 v1.0.0/go.mod h1:RNJv0H/pOIVgxw6KS7QeX2a0Uo0aKUlfhZ4xuwvCdJw= 3 | github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 4 | github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= 5 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 6 | github.com/gtank/merlin v0.1.1 h1:eQ90iG7K9pOhtereWsmyRJ6RAwcP4tHTDBHXNg+u5is= 7 | github.com/gtank/merlin v0.1.1/go.mod h1:T86dnYJhcGOh5BjZFCJWTDeTK7XW8uE+E21Cy/bIQ+s= 8 | github.com/gtank/ristretto255 v0.1.2 h1:JEqUCPA1NvLq5DwYtuzigd7ss8fwbYay9fi4/5uMzcc= 9 | github.com/gtank/ristretto255 v0.1.2/go.mod h1:Ph5OpO6c7xKUGROZfWVLiJf9icMDwUeIvY4OmlYW69o= 10 | github.com/mimoo/StrobeGo v0.0.0-20181016162300-f8f6d4d2b643/go.mod h1:43+3pMjjKimDBf5Kr4ZFNGbLql1zKkbImw+fZbw3geM= 11 | github.com/mimoo/StrobeGo v0.0.0-20220103164710-9a04d6ca976b h1:QrHweqAtyJ9EwCaGHBu1fghwxIPiopAHV06JlXrMHjk= 12 | github.com/mimoo/StrobeGo v0.0.0-20220103164710-9a04d6ca976b/go.mod h1:xxLb2ip6sSUts3g1irPVHyk/DGslwQsNOo9I7smJfNU= 13 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= 14 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 15 | github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= 16 | github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= 17 | github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg= 18 | github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= 19 | golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= 20 | golang.org/x/crypto v0.0.0-20200728195943-123391ffb6de/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= 21 | golang.org/x/crypto v0.29.0 h1:L5SG1JTTXupVV3n6sUqMTeWbjAyfPwoda2DLX8J8FrQ= 22 | golang.org/x/crypto v0.29.0/go.mod h1:+F4F4N5hv6v38hfeYwTdx20oUvLLc+QfrE9Ax9HtgRg= 23 | golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= 24 | golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 25 | golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 26 | golang.org/x/sys v0.27.0 h1:wBqf8DvsY9Y/2P8gAfPDEYNuS30J4lPHJxXSb/nJZ+s= 27 | golang.org/x/sys v0.27.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= 28 | golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= 29 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= 30 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 31 | gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 32 | gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= 33 | gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 34 | -------------------------------------------------------------------------------- /helpers.go: -------------------------------------------------------------------------------- 1 | package schnorrkel 2 | 3 | import ( 4 | "crypto/rand" 5 | "encoding/hex" 6 | "errors" 7 | "strings" 8 | 9 | "github.com/gtank/merlin" 10 | r255 "github.com/gtank/ristretto255" 11 | ) 12 | 13 | func challengeScalar(t *merlin.Transcript, msg []byte) *r255.Scalar { 14 | scb := t.ExtractBytes(msg, 64) 15 | sc := r255.NewScalar() 16 | sc.FromUniformBytes(scb) 17 | return sc 18 | } 19 | 20 | // https://github.com/w3f/schnorrkel/blob/718678e51006d84c7d8e4b6cde758906172e74f8/src/scalars.rs#L18 21 | func divideScalarByCofactor(s []byte) []byte { 22 | l := len(s) - 1 23 | low := byte(0) 24 | for i := range s { 25 | r := s[l-i] & 0x07 // remainder 26 | s[l-i] >>= 3 27 | s[l-i] += low 28 | low = r << 5 29 | } 30 | 31 | return s 32 | } 33 | 34 | // NewRandomElement returns a random ristretto element 35 | func NewRandomElement() (*r255.Element, error) { 36 | e := r255.NewElement() 37 | s := [64]byte{} 38 | _, err := rand.Read(s[:]) 39 | if err != nil { 40 | return nil, err 41 | } 42 | 43 | return e.FromUniformBytes(s[:]), nil 44 | } 45 | 46 | // NewRandomScalar returns a random ristretto scalar 47 | func NewRandomScalar() (*r255.Scalar, error) { 48 | s := [64]byte{} 49 | _, err := rand.Read(s[:]) 50 | if err != nil { 51 | return nil, err 52 | } 53 | 54 | ss := r255.NewScalar() 55 | sc := ss.FromUniformBytes(s[:]) 56 | if sc.Equal(r255.NewScalar()) == 1 { 57 | return nil, errors.New("scalar generated was zero") 58 | } 59 | 60 | return sc, nil 61 | } 62 | 63 | // ScalarFromBytes returns a ristretto scalar from the input bytes 64 | // performs input mod l where l is the group order 65 | func ScalarFromBytes(b [32]byte) (*r255.Scalar, error) { 66 | s := r255.NewScalar() 67 | err := s.Decode(b[:]) 68 | if err != nil { 69 | return nil, err 70 | } 71 | 72 | return s, nil 73 | } 74 | 75 | // HexToBytes turns a 0x prefixed hex string into a byte slice 76 | func HexToBytes(in string) ([]byte, error) { 77 | if len(in) < 2 { 78 | return nil, errors.New("invalid string") 79 | } 80 | 81 | if strings.Compare(in[:2], "0x") != 0 { 82 | return nil, errors.New("could not byteify non 0x prefixed string") 83 | } 84 | 85 | if len(in)%2 != 0 { 86 | return nil, errors.New("cannot decode a odd length string") 87 | } 88 | 89 | in = in[2:] 90 | out, err := hex.DecodeString(in) 91 | return out, err 92 | } 93 | -------------------------------------------------------------------------------- /keys.go: -------------------------------------------------------------------------------- 1 | package schnorrkel 2 | 3 | import ( 4 | "crypto/rand" 5 | "crypto/sha512" 6 | "errors" 7 | 8 | "github.com/gtank/merlin" 9 | r255 "github.com/gtank/ristretto255" 10 | ) 11 | 12 | const ( 13 | // MiniSecretKeySize is the length in bytes of a MiniSecretKey 14 | MiniSecretKeySize = 32 15 | 16 | // SecretKeySize is the length in bytes of a SecretKey 17 | SecretKeySize = 32 18 | 19 | // PublicKeySize is the length in bytes of a PublicKey 20 | PublicKeySize = 32 21 | ) 22 | 23 | var ( 24 | publicKeyAtInfinity = r255.NewElement().ScalarBaseMult(r255.NewScalar()) 25 | ErrPublicKeyAtInfinity = errors.New("public key is the point at infinity") 26 | ) 27 | 28 | // MiniSecretKey is a secret scalar 29 | type MiniSecretKey struct { 30 | key [MiniSecretKeySize]byte 31 | } 32 | 33 | // SecretKey consists of a secret scalar and a signing nonce 34 | type SecretKey struct { 35 | key [32]byte // TODO: change this to a *r255.Scalar 36 | nonce [32]byte 37 | } 38 | 39 | // PublicKey is a field element 40 | type PublicKey struct { 41 | key *r255.Element 42 | compressedKey [PublicKeySize]byte 43 | } 44 | 45 | // Keypair consists of a PublicKey and a SecretKey 46 | type Keypair struct { 47 | publicKey *PublicKey 48 | secretKey *SecretKey 49 | } 50 | 51 | // GenerateKeypair generates a new schnorrkel secret key and public key 52 | func GenerateKeypair() (*SecretKey, *PublicKey, error) { 53 | // decodes priv bytes as little-endian 54 | msc, err := GenerateMiniSecretKey() 55 | if err != nil { 56 | return nil, nil, err 57 | } 58 | return msc.ExpandEd25519(), msc.Public(), nil 59 | } 60 | 61 | // NewMiniSecretKey derives a mini secret key from a seed 62 | func NewMiniSecretKey(b [64]byte) *MiniSecretKey { 63 | s := r255.NewScalar() 64 | s.FromUniformBytes(b[:]) 65 | enc := s.Encode([]byte{}) 66 | sk := [MiniSecretKeySize]byte{} 67 | copy(sk[:], enc) 68 | return &MiniSecretKey{key: sk} 69 | } 70 | 71 | // NewMiniSecretKeyFromRaw derives a mini secret key from little-endian encoded raw bytes. 72 | func NewMiniSecretKeyFromRaw(b [MiniSecretKeySize]byte) (*MiniSecretKey, error) { 73 | s := b 74 | return &MiniSecretKey{key: s}, nil 75 | } 76 | 77 | // NewMiniSecretKeyFromHex returns a new MiniSecretKey from the given hex-encoded string 78 | func NewMiniSecretKeyFromHex(s string) (*MiniSecretKey, error) { 79 | b, err := HexToBytes(s) 80 | if err != nil { 81 | return nil, err 82 | } 83 | 84 | pk := [32]byte{} 85 | copy(pk[:], b) 86 | 87 | priv, err := NewMiniSecretKeyFromRaw(pk) 88 | if err != nil { 89 | return nil, err 90 | } 91 | 92 | return priv, nil 93 | } 94 | 95 | // GenerateMiniSecretKey generates a mini secret key from random 96 | func GenerateMiniSecretKey() (*MiniSecretKey, error) { 97 | s := [MiniSecretKeySize]byte{} 98 | _, err := rand.Read(s[:]) 99 | if err != nil { 100 | return nil, err 101 | } 102 | 103 | return &MiniSecretKey{key: s}, nil 104 | } 105 | 106 | // NewSecretKey creates a new secret key from input bytes 107 | func NewSecretKey(key [SecretKeySize]byte, nonce [32]byte) *SecretKey { 108 | return &SecretKey{ 109 | key: key, 110 | nonce: nonce, 111 | } 112 | } 113 | 114 | func NewSecretKeyFromEd25519Bytes(b [SecretKeySize + 32]byte) *SecretKey { 115 | sk := &SecretKey{ 116 | key: [SecretKeySize]byte{}, 117 | nonce: [32]byte{}, 118 | } 119 | 120 | copy(sk.key[:], b[:SecretKeySize]) 121 | divideScalarByCofactor(sk.key[:]) 122 | 123 | copy(sk.nonce[:], b[32:]) 124 | 125 | return sk 126 | } 127 | 128 | // NewPublicKey creates a new public key from input bytes 129 | func NewPublicKey(b [PublicKeySize]byte) (*PublicKey, error) { 130 | e := r255.NewElement() 131 | err := e.Decode(b[:]) 132 | if err != nil { 133 | return nil, err 134 | } 135 | 136 | return &PublicKey{ 137 | key: e, 138 | }, nil 139 | } 140 | 141 | // NewKeypair creates a new keypair from a public key and secret key 142 | func NewKeypair(pk *PublicKey, sk *SecretKey) *Keypair { 143 | return &Keypair{ 144 | publicKey: pk, 145 | secretKey: sk, 146 | } 147 | } 148 | 149 | // NewPublicKeyFromHex returns a PublicKey from a hex-encoded string 150 | func NewPublicKeyFromHex(s string) (*PublicKey, error) { 151 | pubhex, err := HexToBytes(s) 152 | if err != nil { 153 | return nil, err 154 | } 155 | 156 | in := [32]byte{} 157 | copy(in[:], pubhex) 158 | 159 | pub := &PublicKey{} 160 | err = pub.Decode(in) 161 | if err != nil { 162 | return nil, err 163 | } 164 | 165 | return pub, nil 166 | } 167 | 168 | // Decode creates a MiniSecretKey from the given input 169 | func (miniSecretKey *MiniSecretKey) Decode(in [MiniSecretKeySize]byte) error { 170 | msc, err := NewMiniSecretKeyFromRaw(in) 171 | if err != nil { 172 | return err 173 | } 174 | 175 | miniSecretKey.key = msc.key 176 | return nil 177 | } 178 | 179 | // Encode returns the MiniSecretKey's underlying bytes 180 | func (miniSecretKey *MiniSecretKey) Encode() [MiniSecretKeySize]byte { 181 | return miniSecretKey.key 182 | } 183 | 184 | // ExpandUniform expands a MiniSecretKey into a SecretKey 185 | func (miniSecretKey *MiniSecretKey) ExpandUniform() *SecretKey { 186 | t := merlin.NewTranscript("ExpandSecretKeys") 187 | t.AppendMessage([]byte("mini"), miniSecretKey.key[:]) 188 | scalarBytes := t.ExtractBytes([]byte("sk"), 64) 189 | key := r255.NewScalar() 190 | key.FromUniformBytes(scalarBytes[:]) 191 | nonce := t.ExtractBytes([]byte("no"), 32) 192 | key32 := [32]byte{} 193 | copy(key32[:], key.Encode([]byte{})) 194 | nonce32 := [32]byte{} 195 | copy(nonce32[:], nonce) 196 | return &SecretKey{ 197 | key: key32, 198 | nonce: nonce32, 199 | } 200 | } 201 | 202 | // ExpandEd25519 expands a MiniSecretKey into a SecretKey using ed25519-style bit clamping 203 | // https://github.com/w3f/schnorrkel/blob/43f7fc00724edd1ef53d5ae13d82d240ed6202d5/src/keys.rs#L196 204 | func (miniSecretKey *MiniSecretKey) ExpandEd25519() *SecretKey { 205 | h := sha512.Sum512(miniSecretKey.key[:]) 206 | sk := &SecretKey{ 207 | key: [SecretKeySize]byte{}, 208 | nonce: [32]byte{}, 209 | } 210 | 211 | copy(sk.key[:], h[:32]) 212 | 213 | sk.key[0] &= 248 214 | sk.key[31] &= 63 215 | sk.key[31] |= 64 216 | t := divideScalarByCofactor(sk.key[:]) 217 | 218 | copy(sk.key[:], t) 219 | copy(sk.nonce[:], h[32:]) 220 | return sk 221 | } 222 | 223 | // Public returns the PublicKey expanded from this MiniSecretKey using ExpandEd25519 224 | func (miniSecretKey *MiniSecretKey) Public() *PublicKey { 225 | e := r255.NewElement() 226 | sk := miniSecretKey.ExpandEd25519() 227 | skey, err := ScalarFromBytes(sk.key) 228 | if err != nil { 229 | return nil 230 | } 231 | 232 | return &PublicKey{key: e.ScalarBaseMult(skey)} 233 | } 234 | 235 | // Decode creates a SecretKey from the given input 236 | func (secretKey *SecretKey) Decode(in [SecretKeySize]byte) error { 237 | secretKey.key = in 238 | return nil 239 | } 240 | 241 | // Encode returns the SecretKey's underlying bytes 242 | func (secretKey *SecretKey) Encode() [SecretKeySize]byte { 243 | return secretKey.key 244 | } 245 | 246 | // Public gets the public key corresponding to this SecretKey 247 | func (secretKey *SecretKey) Public() (*PublicKey, error) { 248 | e := r255.NewElement() 249 | sc, err := ScalarFromBytes(secretKey.key) 250 | if err != nil { 251 | return nil, err 252 | } 253 | return &PublicKey{key: e.ScalarBaseMult(sc)}, nil 254 | } 255 | 256 | // Keypair returns the keypair corresponding to this SecretKey 257 | func (secretKey *SecretKey) Keypair() (*Keypair, error) { 258 | pub, err := secretKey.Public() 259 | if err != nil { 260 | return nil, err 261 | } 262 | return NewKeypair(pub, secretKey), nil 263 | } 264 | 265 | // Decode creates a PublicKey from the given input 266 | func (publicKey *PublicKey) Decode(in [PublicKeySize]byte) error { 267 | publicKey.key = r255.NewElement() 268 | return publicKey.key.Decode(in[:]) 269 | } 270 | 271 | // Encode returns the encoded point underlying the public key 272 | func (publicKey *PublicKey) Encode() [PublicKeySize]byte { 273 | if publicKey.compressedKey != [PublicKeySize]byte{} { 274 | return publicKey.compressedKey 275 | } 276 | b := publicKey.key.Encode([]byte{}) 277 | enc := [PublicKeySize]byte{} 278 | copy(enc[:], b) 279 | publicKey.compressedKey = enc 280 | return enc 281 | } 282 | -------------------------------------------------------------------------------- /keys_test.go: -------------------------------------------------------------------------------- 1 | package schnorrkel 2 | 3 | import ( 4 | "encoding/hex" 5 | "testing" 6 | 7 | "github.com/stretchr/testify/require" 8 | ) 9 | 10 | func TestGenerateKeypair(t *testing.T) { 11 | priv, pub, err := GenerateKeypair() 12 | require.NoError(t, err) 13 | require.NotNil(t, priv) 14 | require.NotNil(t, pub) 15 | 16 | pub2, err := priv.Public() 17 | require.NoError(t, err) 18 | require.Equal(t, pub.key.Encode([]byte{}), pub2.key.Encode([]byte{})) 19 | } 20 | 21 | func TestGenerateKeypairFromSecretKey(t *testing.T) { 22 | priv, pub, err := GenerateKeypair() 23 | require.NoError(t, err) 24 | require.NotNil(t, priv) 25 | require.NotNil(t, pub) 26 | 27 | kp, err := priv.Keypair() 28 | require.NoError(t, err) 29 | require.Equal(t, pub.key.Encode([]byte{}), kp.publicKey.key.Encode([]byte{})) 30 | } 31 | 32 | // test cases from: https://github.com/Warchant/sr25519-crust/blob/master/test/keypair_from_seed.cpp 33 | func TestMiniSecretKey_ExpandEd25519(t *testing.T) { 34 | msc, err := NewMiniSecretKeyFromRaw([32]byte{}) 35 | require.NoError(t, err) 36 | 37 | sc := msc.ExpandEd25519() 38 | 39 | expected, err := hex.DecodeString("caa835781b15c7706f65b71f7a58c807ab360faed6440fb23e0f4c52e930de0a0a6a85eaa642dac835424b5d7c8d637c00408c7a73da672b7f498521420b6dd3def12e42f3e487e9b14095aa8d5cc16a33491f1b50dadcf8811d1480f3fa8627") 40 | require.NoError(t, err) 41 | require.Equal(t, expected[:32], sc.key[:]) 42 | require.Equal(t, expected[32:64], sc.nonce[:]) 43 | 44 | pub := msc.Public().Encode() 45 | require.Equal(t, expected[64:], pub[:]) 46 | } 47 | 48 | func TestMiniSecretKey_Public(t *testing.T) { 49 | // test vectors from https://github.com/noot/schnorrkel/blob/master/src/keys.rs#L996 50 | raw := [32]byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2} 51 | msc, err := NewMiniSecretKeyFromRaw(raw) 52 | require.NoError(t, err) 53 | 54 | sc := msc.ExpandEd25519() 55 | expectedKey := []byte{11, 241, 180, 83, 213, 181, 31, 180, 138, 45, 144, 84, 2, 78, 47, 81, 225, 208, 202, 53, 128, 52, 89, 144, 36, 92, 197, 51, 166, 28, 152, 10} 56 | expectedNonce := []byte{69, 121, 245, 84, 53, 88, 241, 101, 252, 126, 198, 17, 237, 114, 215, 135, 224, 58, 4, 75, 134, 169, 226, 109, 76, 133, 25, 135, 115, 81, 176, 46} 57 | expectedPubkey := []byte{140, 122, 228, 195, 50, 29, 229, 250, 94, 159, 183, 123, 208, 116, 7, 78, 229, 29, 247, 64, 172, 187, 92, 144, 121, 56, 242, 3, 116, 99, 100, 32} 58 | 59 | require.Equal(t, expectedKey, sc.key[:]) 60 | require.Equal(t, expectedNonce, sc.nonce[:]) 61 | 62 | pub := msc.Public().Encode() 63 | require.Equal(t, expectedPubkey, pub[:]) 64 | } 65 | 66 | func TestPublicKey_Decode(t *testing.T) { 67 | // test vectors from https://github.com/Warchant/sr25519-crust/blob/master/test/ds.cpp#L48 68 | pubhex, err := hex.DecodeString("46ebddef8cd9bb167dc30878d7113b7e168e6f0646beffd77d69d39bad76b47a") 69 | require.NoError(t, err) 70 | 71 | in := [32]byte{} 72 | copy(in[:], pubhex) 73 | 74 | pub := &PublicKey{} 75 | err = pub.Decode(in) 76 | require.NoError(t, err) 77 | 78 | privhex, err := hex.DecodeString("05d65584630d16cd4af6d0bec10f34bb504a5dcb62dba2122d49f5a663763d0a") 79 | require.NoError(t, err) 80 | 81 | copy(in[:], privhex) 82 | priv := &SecretKey{} 83 | err = priv.Decode(in) 84 | require.NoError(t, err) 85 | 86 | expected, err := priv.Public() 87 | require.NoError(t, err) 88 | 89 | pubcmp := pub.Encode() 90 | expcmp := expected.Encode() 91 | require.Equal(t, expcmp[:], pubcmp[:]) 92 | } 93 | 94 | func TestNewPublicKey(t *testing.T) { 95 | pub := [32]byte{140, 122, 228, 195, 50, 29, 229, 250, 94, 159, 183, 123, 208, 116, 7, 78, 229, 29, 247, 64, 172, 187, 92, 144, 121, 56, 242, 3, 116, 99, 100, 32} 96 | pk, err := NewPublicKey(pub) 97 | require.NoError(t, err) 98 | 99 | enc := pk.Encode() 100 | require.Equal(t, pub[:], enc[:]) 101 | } 102 | 103 | func TestNewSecretKeyFromEd25519Bytes(t *testing.T) { 104 | // test vectors from https://github.com/w3f/schnorrkel/blob/ab3e3d609cd8b9eefbe0333066f698c40fd09582/src/keys.rs#L504-L507 105 | b := [64]byte{} 106 | byteshex, err := hex.DecodeString("28b0ae221c6bb06856b287f60d7ea0d98552ea5a16db16956849aa371db3eb51fd190cce74df356432b410bd64682309d6dedb27c76845daf388557cbac3ca34") 107 | require.NoError(t, err) 108 | copy(b[:], byteshex) 109 | 110 | pub := [32]byte{} 111 | pubhex, err := hex.DecodeString("46ebddef8cd9bb167dc30878d7113b7e168e6f0646beffd77d69d39bad76b47a") 112 | require.NoError(t, err) 113 | copy(pub[:], pubhex) 114 | 115 | sc := NewSecretKeyFromEd25519Bytes(b) 116 | pk, err := sc.Public() 117 | require.NoError(t, err) 118 | require.Equal(t, pub, pk.Encode()) 119 | } 120 | -------------------------------------------------------------------------------- /sign.go: -------------------------------------------------------------------------------- 1 | package schnorrkel 2 | 3 | import ( 4 | "errors" 5 | 6 | "github.com/gtank/merlin" 7 | r255 "github.com/gtank/ristretto255" 8 | ) 9 | 10 | // SignatureSize is the length in bytes of a signature 11 | const SignatureSize = 64 12 | 13 | // ErrSignatureNotMarkedSchnorrkel is returned when attempting to decode a signature that is not marked as schnorrkel 14 | var ErrSignatureNotMarkedSchnorrkel = errors.New("signature is not marked as a schnorrkel signature") 15 | 16 | // Signature holds a schnorrkel signature 17 | type Signature struct { 18 | r *r255.Element 19 | s *r255.Scalar 20 | } 21 | 22 | // NewSignatureFromHex returns a new Signature from the given hex-encoded string 23 | func NewSignatureFromHex(s string) (*Signature, error) { 24 | sighex, err := HexToBytes(s) 25 | if err != nil { 26 | return nil, err 27 | } 28 | 29 | sigin := [64]byte{} 30 | copy(sigin[:], sighex) 31 | 32 | sig := &Signature{} 33 | err = sig.Decode(sigin) 34 | if err != nil { 35 | return nil, err 36 | } 37 | 38 | return sig, nil 39 | } 40 | 41 | // NewSigningContext returns a new transcript initialized with the context for the signature 42 | // .see: https://github.com/w3f/schnorrkel/blob/db61369a6e77f8074eb3247f9040ccde55697f20/src/context.rs#L183 43 | func NewSigningContext(context, msg []byte) *merlin.Transcript { 44 | t := merlin.NewTranscript("SigningContext") 45 | t.AppendMessage([]byte(""), context) 46 | t.AppendMessage([]byte("sign-bytes"), msg) 47 | return t 48 | } 49 | 50 | // Sign uses the schnorr signature algorithm to sign a message 51 | // See the following for the transcript message 52 | // https://github.com/w3f/schnorrkel/blob/db61369a6e77f8074eb3247f9040ccde55697f20/src/sign.rs#L158 53 | // Schnorr w/ transcript, secret key x: 54 | // 1. choose random r from group 55 | // 2. R = gr 56 | // 3. k = scalar(transcript.extract_bytes()) 57 | // 4. s = kx + r 58 | // signature: (R, s) 59 | // public key used for verification: y = g^x 60 | func (secretKey *SecretKey) Sign(t *merlin.Transcript) (*Signature, error) { 61 | t.AppendMessage([]byte("proto-name"), []byte("Schnorr-sig")) 62 | 63 | pub, err := secretKey.Public() 64 | if err != nil { 65 | return nil, err 66 | } 67 | pubc := pub.Encode() 68 | 69 | t.AppendMessage([]byte("sign:pk"), pubc[:]) 70 | 71 | // note: TODO: merlin library doesn't have build_rng yet. 72 | // see https://github.com/w3f/schnorrkel/blob/798ab3e0813aa478b520c5cf6dc6e02fd4e07f0a/src/context.rs#L153 73 | // r := t.ExtractBytes([]byte("signing"), 32) 74 | 75 | // choose random r (nonce) 76 | r, err := NewRandomScalar() 77 | if err != nil { 78 | return nil, err 79 | } 80 | R := r255.NewElement().ScalarBaseMult(r) 81 | t.AppendMessage([]byte("sign:R"), R.Encode([]byte{})) 82 | 83 | // form k 84 | kb := t.ExtractBytes([]byte("sign:c"), 64) 85 | k := r255.NewScalar() 86 | k.FromUniformBytes(kb) 87 | 88 | // form scalar from secret key x 89 | x, err := ScalarFromBytes(secretKey.key) 90 | if err != nil { 91 | return nil, err 92 | } 93 | 94 | // s = kx + r 95 | s := x.Multiply(x, k).Add(x, r) 96 | 97 | return &Signature{ 98 | r: R, 99 | s: s, 100 | }, nil 101 | } 102 | 103 | // Sign uses the schnorr signature algorithm to sign a message 104 | // See the following for the transcript message 105 | // https://github.com/w3f/schnorrkel/blob/db61369a6e77f8074eb3247f9040ccde55697f20/src/sign.rs#L158 106 | // Schnorr w/ transcript, secret key x: 107 | // 1. choose random r from group 108 | // 2. R = gr 109 | // 3. k = scalar(transcript.extract_bytes()) 110 | // 4. s = kx + r 111 | // signature: (R, s) 112 | // public key used for verification: y = g^x 113 | func (kp *Keypair) Sign(t *merlin.Transcript) (*Signature, error) { 114 | if kp.secretKey == nil { 115 | return nil, errors.New("secretKey is nil") 116 | } 117 | return kp.secretKey.Sign(t) 118 | } 119 | 120 | // Verify verifies a schnorr signature with format: (R, s) where y is the public key 121 | // 1. k = scalar(transcript.extract_bytes()) 122 | // 2. R' = -ky + gs 123 | // 3. return R' == R 124 | func (publicKey *PublicKey) Verify(s *Signature, t *merlin.Transcript) (bool, error) { 125 | if s == nil { 126 | return false, errors.New("signature provided is nil") 127 | } 128 | 129 | if t == nil { 130 | return false, errors.New("transcript provided is nil") 131 | } 132 | 133 | if publicKey.key.Equal(publicKeyAtInfinity) == 1 { 134 | return false, ErrPublicKeyAtInfinity 135 | } 136 | 137 | t.AppendMessage([]byte("proto-name"), []byte("Schnorr-sig")) 138 | pubc := publicKey.Encode() 139 | t.AppendMessage([]byte("sign:pk"), pubc[:]) 140 | t.AppendMessage([]byte("sign:R"), s.r.Encode([]byte{})) 141 | 142 | kb := t.ExtractBytes([]byte("sign:c"), 64) 143 | k := r255.NewScalar() 144 | k.FromUniformBytes(kb) 145 | 146 | Rp := r255.NewElement().VarTimeDoubleScalarBaseMult(k, r255.NewElement().Negate(publicKey.key), s.s) 147 | 148 | return Rp.Equal(s.r) == 1, nil 149 | } 150 | 151 | // Verify verifies a schnorr signature with format: (R, s) where y is the public key 152 | // 1. k = scalar(transcript.extract_bytes()) 153 | // 2. R' = -ky + gs 154 | // 3. return R' == R 155 | func (kp *Keypair) Verify(s *Signature, t *merlin.Transcript) (bool, error) { 156 | if kp.publicKey == nil { 157 | return false, errors.New("publicKey is nil") 158 | } 159 | return kp.publicKey.Verify(s, t) 160 | } 161 | 162 | // Decode sets a Signature from bytes 163 | // see: https://github.com/w3f/schnorrkel/blob/db61369a6e77f8074eb3247f9040ccde55697f20/src/sign.rs#L100 164 | func (s *Signature) Decode(in [SignatureSize]byte) error { 165 | if in[63]&128 == 0 { 166 | return ErrSignatureNotMarkedSchnorrkel 167 | } 168 | 169 | cp := [64]byte{} 170 | copy(cp[:], in[:]) 171 | 172 | s.r = r255.NewElement() 173 | err := s.r.Decode(cp[:32]) 174 | if err != nil { 175 | return err 176 | } 177 | 178 | cp[63] &= 127 179 | s.s = r255.NewScalar() 180 | return s.s.Decode(cp[32:]) 181 | } 182 | 183 | // Encode turns a signature into a byte array 184 | // see: https://github.com/w3f/schnorrkel/blob/db61369a6e77f8074eb3247f9040ccde55697f20/src/sign.rs#L77 185 | func (s *Signature) Encode() [SignatureSize]byte { 186 | out := [64]byte{} 187 | renc := s.r.Encode([]byte{}) 188 | copy(out[:32], renc) 189 | senc := s.s.Encode([]byte{}) 190 | copy(out[32:], senc) 191 | out[63] |= 128 192 | return out 193 | } 194 | 195 | // DecodeNotDistinguishedFromEd25519 sets a signature from bytes, not checking if the signature 196 | // is explicitly marked as a schnorrkel signature 197 | func (s *Signature) DecodeNotDistinguishedFromEd25519(in [SignatureSize]byte) error { 198 | cp := [64]byte{} 199 | copy(cp[:], in[:]) 200 | cp[63] |= 128 201 | return s.Decode(cp) 202 | } 203 | 204 | // Equal returns true if the two signatures are equal 205 | func (s *Signature) Equal(other *Signature) bool { 206 | return s.r.Equal(other.r) == 1 && s.s.Equal(other.s) == 1 207 | } 208 | -------------------------------------------------------------------------------- /sign_test.go: -------------------------------------------------------------------------------- 1 | package schnorrkel_test 2 | 3 | import ( 4 | "encoding/hex" 5 | "testing" 6 | 7 | "github.com/ChainSafe/go-schnorrkel" 8 | r255 "github.com/gtank/ristretto255" 9 | 10 | "github.com/gtank/merlin" 11 | "github.com/stretchr/testify/require" 12 | ) 13 | 14 | func TestSignAndVerify(t *testing.T) { 15 | transcript := merlin.NewTranscript("hello") 16 | priv, pub, err := schnorrkel.GenerateKeypair() 17 | require.NoError(t, err) 18 | 19 | sig, err := priv.Sign(transcript) 20 | require.NoError(t, err) 21 | 22 | transcript2 := merlin.NewTranscript("hello") 23 | ok, err := pub.Verify(sig, transcript2) 24 | require.NoError(t, err) 25 | require.True(t, ok) 26 | } 27 | 28 | func TestSignAndVerifyKeypair(t *testing.T) { 29 | transcript := merlin.NewTranscript("hello") 30 | priv, pub, err := schnorrkel.GenerateKeypair() 31 | require.NoError(t, err) 32 | 33 | kp := schnorrkel.NewKeypair(pub, priv) 34 | 35 | sig, err := kp.Sign(transcript) 36 | require.NoError(t, err) 37 | 38 | transcript2 := merlin.NewTranscript("hello") 39 | ok, err := pub.Verify(sig, transcript2) 40 | require.NoError(t, err) 41 | require.True(t, ok) 42 | } 43 | 44 | func TestVerify(t *testing.T) { 45 | transcript := merlin.NewTranscript("hello") 46 | priv, pub, err := schnorrkel.GenerateKeypair() 47 | require.NoError(t, err) 48 | 49 | sig, err := priv.Sign(transcript) 50 | require.NoError(t, err) 51 | 52 | transcript2 := merlin.NewTranscript("hello") 53 | ok, err := pub.Verify(sig, transcript2) 54 | require.NoError(t, err) 55 | require.True(t, ok) 56 | 57 | transcript3 := merlin.NewTranscript("hello") 58 | ok, err = pub.Verify(sig, transcript3) 59 | require.NoError(t, err) 60 | require.True(t, ok) 61 | } 62 | 63 | func TestVerifyKeypair(t *testing.T) { 64 | transcript := merlin.NewTranscript("hello") 65 | priv, pub, err := schnorrkel.GenerateKeypair() 66 | require.NoError(t, err) 67 | 68 | kp := schnorrkel.NewKeypair(pub, priv) 69 | sig, err := kp.Sign(transcript) 70 | require.NoError(t, err) 71 | 72 | transcript2 := merlin.NewTranscript("hello") 73 | ok, err := kp.Verify(sig, transcript2) 74 | require.NoError(t, err) 75 | require.True(t, ok) 76 | 77 | transcript3 := merlin.NewTranscript("hello") 78 | ok, err = kp.Verify(sig, transcript3) 79 | require.NoError(t, err) 80 | require.True(t, ok) 81 | } 82 | 83 | func TestSignature_EncodeAndDecode(t *testing.T) { 84 | transcript := merlin.NewTranscript("hello") 85 | priv, _, err := schnorrkel.GenerateKeypair() 86 | require.NoError(t, err) 87 | 88 | sig, err := priv.Sign(transcript) 89 | require.NoError(t, err) 90 | 91 | enc := sig.Encode() 92 | 93 | res := &schnorrkel.Signature{} 94 | err = res.Decode(enc) 95 | require.NoError(t, err) 96 | 97 | require.True(t, sig.Equal(res)) 98 | } 99 | 100 | func TestVerify_rust(t *testing.T) { 101 | signingContext := []byte("substrate") 102 | // test vectors from https://github.com/Warchant/sr25519-crust/blob/master/test/ds.cpp#L48 103 | pubhex, err := hex.DecodeString("46ebddef8cd9bb167dc30878d7113b7e168e6f0646beffd77d69d39bad76b47a") 104 | require.NoError(t, err) 105 | 106 | in := [32]byte{} 107 | copy(in[:], pubhex) 108 | 109 | pub := &schnorrkel.PublicKey{} 110 | err = pub.Decode(in) 111 | require.NoError(t, err) 112 | 113 | msg := []byte("this is a message") 114 | sighex, err := hex.DecodeString("4e172314444b8f820bb54c22e95076f220ed25373e5c178234aa6c211d29271244b947e3ff3418ff6b45fd1df1140c8cbff69fc58ee6dc96df70936a2bb74b82") 115 | require.NoError(t, err) 116 | 117 | sigin := [64]byte{} 118 | copy(sigin[:], sighex) 119 | 120 | sig := &schnorrkel.Signature{} 121 | err = sig.Decode(sigin) 122 | require.NoError(t, err) 123 | 124 | transcript := schnorrkel.NewSigningContext(signingContext, msg) 125 | ok, err := pub.Verify(sig, transcript) 126 | require.NoError(t, err) 127 | require.True(t, ok) 128 | } 129 | 130 | func TestVerify_PublicKeyAtInfinity(t *testing.T) { 131 | publicKeyAtInfinity := r255.NewElement().ScalarBaseMult(r255.NewScalar()) 132 | transcript := merlin.NewTranscript("hello") 133 | priv := schnorrkel.SecretKey{} 134 | pub, err := priv.Public() 135 | require.NoError(t, err) 136 | enc := pub.Encode() 137 | require.Equal(t, publicKeyAtInfinity.Encode([]byte{}), enc[:]) 138 | 139 | sig, err := priv.Sign(transcript) 140 | require.NoError(t, err) 141 | 142 | transcript2 := merlin.NewTranscript("hello") 143 | _, err = pub.Verify(sig, transcript2) 144 | require.ErrorIs(t, err, schnorrkel.ErrPublicKeyAtInfinity) 145 | } 146 | -------------------------------------------------------------------------------- /vrf.go: -------------------------------------------------------------------------------- 1 | package schnorrkel 2 | 3 | import ( 4 | "errors" 5 | 6 | "github.com/gtank/merlin" 7 | r255 "github.com/gtank/ristretto255" 8 | ) 9 | 10 | // MAX_VRF_BYTES is the maximum bytes that can be extracted from the VRF via MakeBytes 11 | const MAX_VRF_BYTES = 64 12 | 13 | var kusamaVRF = true 14 | 15 | const VRFLabel = "VRF" 16 | 17 | type VrfInOut struct { 18 | input *r255.Element 19 | output *r255.Element 20 | } 21 | 22 | type VrfOutput struct { 23 | output *r255.Element 24 | } 25 | 26 | type VrfProof struct { 27 | c *r255.Scalar 28 | s *r255.Scalar 29 | } 30 | 31 | // SetKusama sets the VRF kusama option. Defaults to true. 32 | func SetKusamaVRF(k bool) { 33 | kusamaVRF = k 34 | } 35 | 36 | // Output returns a VrfOutput from a VrfInOut 37 | func (io *VrfInOut) Output() *VrfOutput { 38 | return &VrfOutput{ 39 | output: io.output, 40 | } 41 | } 42 | 43 | // EncodeOutput returns the 64-byte encoding of the input and output concatenated 44 | func (io *VrfInOut) Encode() []byte { 45 | outbytes := [32]byte{} 46 | copy(outbytes[:], io.output.Encode([]byte{})) 47 | inbytes := [32]byte{} 48 | copy(inbytes[:], io.input.Encode([]byte{})) 49 | return append(inbytes[:], outbytes[:]...) 50 | } 51 | 52 | // MakeBytes returns raw bytes output from the VRF 53 | // It returns a byte slice of the given size 54 | // https://github.com/w3f/schnorrkel/blob/master/src/vrf.rs#L343 55 | func (io *VrfInOut) MakeBytes(size int, context []byte) ([]byte, error) { 56 | if size <= 0 || size > MAX_VRF_BYTES { 57 | return nil, errors.New("invalid size parameter") 58 | } 59 | 60 | t := merlin.NewTranscript("VRFResult") 61 | t.AppendMessage([]byte(""), context) 62 | io.commit(t) 63 | return t.ExtractBytes([]byte(""), size), nil 64 | } 65 | 66 | func (io *VrfInOut) commit(t *merlin.Transcript) { 67 | t.AppendMessage([]byte("vrf-in"), io.input.Encode([]byte{})) 68 | t.AppendMessage([]byte("vrf-out"), io.output.Encode([]byte{})) 69 | } 70 | 71 | // NewOutput creates a new VRF output from a 64-byte element 72 | func NewOutput(in [32]byte) (*VrfOutput, error) { 73 | output := r255.NewElement() 74 | err := output.Decode(in[:]) 75 | if err != nil { 76 | return nil, err 77 | } 78 | 79 | return &VrfOutput{ 80 | output: output, 81 | }, nil 82 | } 83 | 84 | // AttachInput returns a VrfInOut pair from an output 85 | // https://github.com/w3f/schnorrkel/blob/master/src/vrf.rs#L249 86 | func (out *VrfOutput) AttachInput(pub *PublicKey, t *merlin.Transcript) (*VrfInOut, error) { 87 | if pub == nil { 88 | return nil, errors.New("public key provided is nil") 89 | } 90 | 91 | if t == nil { 92 | return nil, errors.New("transcript provided is nil") 93 | } 94 | 95 | input := pub.vrfHash(t) 96 | return &VrfInOut{ 97 | input: input, 98 | output: out.output, 99 | }, nil 100 | } 101 | 102 | // Encode returns the 32-byte encoding of the output 103 | func (out *VrfOutput) Encode() [32]byte { 104 | outbytes := [32]byte{} 105 | copy(outbytes[:], out.output.Encode([]byte{})) 106 | return outbytes 107 | } 108 | 109 | // Decode sets the VrfOutput to the decoded input 110 | func (out *VrfOutput) Decode(in [32]byte) error { 111 | output := r255.NewElement() 112 | err := output.Decode(in[:]) 113 | if err != nil { 114 | return err 115 | } 116 | out.output = output 117 | return nil 118 | } 119 | 120 | // Encode returns a 64-byte encoded VrfProof 121 | func (p *VrfProof) Encode() [64]byte { 122 | cbytes := [32]byte{} 123 | copy(cbytes[:], p.c.Encode([]byte{})) 124 | sbytes := [32]byte{} 125 | copy(sbytes[:], p.s.Encode([]byte{})) 126 | enc := [64]byte{} 127 | copy(enc[:32], cbytes[:]) 128 | copy(enc[32:], sbytes[:]) 129 | return enc 130 | } 131 | 132 | // Decode sets the VrfProof to the decoded input 133 | func (p *VrfProof) Decode(in [64]byte) error { 134 | c := r255.NewScalar() 135 | err := c.Decode(in[:32]) 136 | if err != nil { 137 | return err 138 | } 139 | p.c = c 140 | 141 | s := r255.NewScalar() 142 | err = s.Decode(in[32:]) 143 | if err != nil { 144 | return err 145 | } 146 | p.s = s 147 | 148 | return nil 149 | } 150 | 151 | // VrfSign returns a vrf output and proof given a secret key and transcript. 152 | func (kp *Keypair) VrfSign(t *merlin.Transcript) (*VrfInOut, *VrfProof, error) { 153 | if kp.secretKey == nil { 154 | return nil, nil, errors.New("secretKey is nil") 155 | } 156 | return kp.secretKey.VrfSign(t) 157 | } 158 | 159 | // VrfVerify verifies that the proof and output created are valid given the public key and transcript. 160 | func (kp *Keypair) VrfVerify(t *merlin.Transcript, out *VrfOutput, proof *VrfProof) (bool, error) { 161 | if kp.publicKey == nil { 162 | return false, errors.New("publicKey is nil") 163 | } 164 | return kp.publicKey.VrfVerify(t, out, proof) 165 | } 166 | 167 | // VrfSign returns a vrf output and proof given a secret key and transcript. 168 | func (secretKey *SecretKey) VrfSign(t *merlin.Transcript) (*VrfInOut, *VrfProof, error) { 169 | if t == nil { 170 | return nil, nil, errors.New("transcript provided is nil") 171 | } 172 | 173 | p, err := secretKey.vrfCreateHash(t) 174 | if err != nil { 175 | return nil, nil, err 176 | } 177 | 178 | extra := merlin.NewTranscript(VRFLabel) 179 | proof, err := secretKey.dleqProve(extra, p) 180 | if err != nil { 181 | return nil, nil, err 182 | } 183 | return p, proof, nil 184 | } 185 | 186 | // dleqProve creates a VRF proof for the transcript and input with this secret key. 187 | // see: https://github.com/w3f/schnorrkel/blob/798ab3e0813aa478b520c5cf6dc6e02fd4e07f0a/src/vrf.rs#L604 188 | func (secretKey *SecretKey) dleqProve(t *merlin.Transcript, p *VrfInOut) (*VrfProof, error) { 189 | pub, err := secretKey.Public() 190 | if err != nil { 191 | return nil, err 192 | } 193 | pubenc := pub.Encode() 194 | 195 | t.AppendMessage([]byte("proto-name"), []byte("DLEQProof")) 196 | t.AppendMessage([]byte("vrf:h"), p.input.Encode([]byte{})) 197 | if !kusamaVRF { 198 | t.AppendMessage([]byte("vrf:pk"), pubenc[:]) 199 | } 200 | 201 | // create random element R = g^r 202 | // TODO: update toe use witness scalar 203 | // https://github.com/w3f/schnorrkel/blob/master/src/vrf.rs#L620 204 | r, err := NewRandomScalar() 205 | if err != nil { 206 | return nil, err 207 | } 208 | R := r255.NewElement() 209 | R.ScalarBaseMult(r) 210 | t.AppendMessage([]byte("vrf:R=g^r"), R.Encode([]byte{})) 211 | 212 | // create hr := HashToElement(input) 213 | hr := r255.NewElement().ScalarMult(r, p.input).Encode([]byte{}) 214 | t.AppendMessage([]byte("vrf:h^r"), hr) 215 | 216 | if kusamaVRF { 217 | t.AppendMessage([]byte("vrf:pk"), pubenc[:]) 218 | } 219 | t.AppendMessage([]byte("vrf:h^sk"), p.output.Encode([]byte{})) 220 | 221 | c := challengeScalar(t, []byte("prove")) 222 | s := r255.NewScalar() 223 | sc, err := ScalarFromBytes(secretKey.key) 224 | if err != nil { 225 | return nil, err 226 | } 227 | s.Subtract(r, r255.NewScalar().Multiply(c, sc)) 228 | 229 | return &VrfProof{ 230 | c: c, 231 | s: s, 232 | }, nil 233 | } 234 | 235 | // vrfCreateHash creates a VRF input/output pair on the given transcript. 236 | func (secretKey *SecretKey) vrfCreateHash(t *merlin.Transcript) (*VrfInOut, error) { 237 | pub, err := secretKey.Public() 238 | if err != nil { 239 | return nil, err 240 | } 241 | input := pub.vrfHash(t) 242 | 243 | output := r255.NewElement() 244 | sc := r255.NewScalar() 245 | err = sc.Decode(secretKey.key[:]) 246 | if err != nil { 247 | return nil, err 248 | } 249 | output.ScalarMult(sc, input) 250 | 251 | return &VrfInOut{ 252 | input: input, 253 | output: output, 254 | }, nil 255 | } 256 | 257 | // VrfVerify verifies that the proof and output created are valid given the public key and transcript. 258 | func (publicKey *PublicKey) VrfVerify(t *merlin.Transcript, out *VrfOutput, proof *VrfProof) (bool, error) { 259 | if t == nil { 260 | return false, errors.New("transcript provided is nil") 261 | } 262 | 263 | if out == nil { 264 | return false, errors.New("output provided is nil") 265 | } 266 | 267 | if proof == nil { 268 | return false, errors.New("proof provided is nil") 269 | } 270 | 271 | if publicKey.key.Equal(publicKeyAtInfinity) == 1 { 272 | return false, ErrPublicKeyAtInfinity 273 | } 274 | 275 | inout, err := out.AttachInput(publicKey, t) 276 | if err != nil { 277 | return false, err 278 | } 279 | 280 | t0 := merlin.NewTranscript(VRFLabel) 281 | return publicKey.dleqVerify(t0, inout, proof) 282 | } 283 | 284 | // dleqVerify verifies the corresponding dleq proof. 285 | func (publicKey *PublicKey) dleqVerify(t *merlin.Transcript, p *VrfInOut, proof *VrfProof) (bool, error) { 286 | t.AppendMessage([]byte("proto-name"), []byte("DLEQProof")) 287 | t.AppendMessage([]byte("vrf:h"), p.input.Encode([]byte{})) 288 | if !kusamaVRF { 289 | t.AppendMessage([]byte("vrf:pk"), publicKey.key.Encode([]byte{})) 290 | } 291 | 292 | // R = proof.c*pk + proof.s*g 293 | R := r255.NewElement() 294 | R.VarTimeDoubleScalarBaseMult(proof.c, publicKey.key, proof.s) 295 | t.AppendMessage([]byte("vrf:R=g^r"), R.Encode([]byte{})) 296 | 297 | // hr = proof.c * p.output + proof.s * p.input 298 | hr := r255.NewElement().VarTimeMultiScalarMult([]*r255.Scalar{proof.c, proof.s}, []*r255.Element{p.output, p.input}) 299 | t.AppendMessage([]byte("vrf:h^r"), hr.Encode([]byte{})) 300 | if kusamaVRF { 301 | t.AppendMessage([]byte("vrf:pk"), publicKey.key.Encode([]byte{})) 302 | } 303 | t.AppendMessage([]byte("vrf:h^sk"), p.output.Encode([]byte{})) 304 | 305 | cexpected := challengeScalar(t, []byte("prove")) 306 | if cexpected.Equal(proof.c) == 1 { 307 | return true, nil 308 | } 309 | 310 | return false, nil 311 | } 312 | 313 | // vrfHash hashes the transcript to a point. 314 | func (publicKey *PublicKey) vrfHash(t *merlin.Transcript) *r255.Element { 315 | mt := TranscriptWithMalleabilityAddressed(t, publicKey) 316 | hash := mt.ExtractBytes([]byte("VRFHash"), 64) 317 | point := r255.NewElement() 318 | point.FromUniformBytes(hash) 319 | return point 320 | } 321 | 322 | // TranscriptWithMalleabilityAddressed returns the input transcript with the public key commited to it, 323 | // addressing VRF output malleability. 324 | func TranscriptWithMalleabilityAddressed(t *merlin.Transcript, pk *PublicKey) *merlin.Transcript { 325 | enc := pk.Encode() 326 | t.AppendMessage([]byte("vrf-nm-pk"), enc[:]) 327 | return t 328 | } 329 | -------------------------------------------------------------------------------- /vrf_test.go: -------------------------------------------------------------------------------- 1 | package schnorrkel 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/gtank/merlin" 7 | r255 "github.com/gtank/ristretto255" 8 | "github.com/stretchr/testify/require" 9 | ) 10 | 11 | func TestKeypairInputAndOutput(t *testing.T) { 12 | signTranscript := merlin.NewTranscript("vrf-test") 13 | verifyTranscript := merlin.NewTranscript("vrf-test") 14 | 15 | priv, pub, err := GenerateKeypair() 16 | require.NoError(t, err) 17 | kp := NewKeypair(pub, priv) 18 | 19 | inout, proof, err := kp.VrfSign(signTranscript) 20 | require.NoError(t, err) 21 | 22 | outslice := inout.output.Encode([]byte{}) 23 | outbytes := [32]byte{} 24 | copy(outbytes[:], outslice) 25 | out, err := NewOutput(outbytes) 26 | require.NoError(t, err) 27 | 28 | ok, err := kp.VrfVerify(verifyTranscript, out, proof) 29 | require.NoError(t, err) 30 | require.True(t, ok) 31 | } 32 | 33 | func TestInputAndOutput(t *testing.T) { 34 | signTranscript := merlin.NewTranscript("vrf-test") 35 | verifyTranscript := merlin.NewTranscript("vrf-test") 36 | 37 | priv, pub, err := GenerateKeypair() 38 | require.NoError(t, err) 39 | 40 | inout, proof, err := priv.VrfSign(signTranscript) 41 | require.NoError(t, err) 42 | 43 | outslice := inout.output.Encode([]byte{}) 44 | outbytes := [32]byte{} 45 | copy(outbytes[:], outslice) 46 | out, err := NewOutput(outbytes) 47 | require.NoError(t, err) 48 | 49 | ok, err := pub.VrfVerify(verifyTranscript, out, proof) 50 | require.NoError(t, err) 51 | require.True(t, ok) 52 | } 53 | 54 | func TestOutput_EncodeAndDecode(t *testing.T) { 55 | o, err := NewRandomElement() 56 | require.NoError(t, err) 57 | 58 | out := &VrfOutput{ 59 | output: o, 60 | } 61 | 62 | enc := out.Encode() 63 | out2 := new(VrfOutput) 64 | err = out2.Decode(enc) 65 | require.NoError(t, err) 66 | 67 | enc2 := out2.Encode() 68 | require.Equal(t, enc[:], enc2[:]) 69 | } 70 | 71 | func TestProof_EncodeAndDecode(t *testing.T) { 72 | c, err := NewRandomScalar() 73 | require.NoError(t, err) 74 | 75 | s, err := NewRandomScalar() 76 | require.NoError(t, err) 77 | 78 | proof := &VrfProof{ 79 | c: c, 80 | s: s, 81 | } 82 | 83 | enc := proof.Encode() 84 | proof2 := new(VrfProof) 85 | err = proof2.Decode(enc) 86 | require.NoError(t, err) 87 | 88 | enc2 := proof2.Encode() 89 | require.Equal(t, enc[:], enc2[:]) 90 | } 91 | 92 | func TestVRFSignAndVerify(t *testing.T) { 93 | signTranscript := merlin.NewTranscript("vrf-test") 94 | verifyTranscript := merlin.NewTranscript("vrf-test") 95 | verify2Transcript := merlin.NewTranscript("vrf-test") 96 | 97 | priv, pub, err := GenerateKeypair() 98 | require.NoError(t, err) 99 | 100 | inout, proof, err := priv.VrfSign(signTranscript) 101 | require.NoError(t, err) 102 | 103 | ok, err := pub.VrfVerify(verifyTranscript, inout.Output(), proof) 104 | require.NoError(t, err) 105 | require.True(t, ok) 106 | 107 | proof.c, err = NewRandomScalar() 108 | require.NoError(t, err) 109 | 110 | ok, err = pub.VrfVerify(verify2Transcript, inout.Output(), proof) 111 | require.NoError(t, err) 112 | require.False(t, ok) 113 | } 114 | 115 | func TestVrfVerify_rust(t *testing.T) { 116 | // test case from https://github.com/w3f/schnorrkel/blob/798ab3e0813aa478b520c5cf6dc6e02fd4e07f0a/src/vrf.rs#L922 117 | pubbytes := [32]byte{192, 42, 72, 186, 20, 11, 83, 150, 245, 69, 168, 222, 22, 166, 167, 95, 125, 248, 184, 67, 197, 10, 161, 107, 205, 116, 143, 164, 143, 127, 166, 84} 118 | pub, err := NewPublicKey(pubbytes) 119 | require.NoError(t, err) 120 | 121 | transcript := NewSigningContext([]byte("yo!"), []byte("meow")) 122 | 123 | inputbytes := []byte{56, 52, 39, 115, 143, 80, 43, 66, 174, 177, 101, 21, 177, 15, 199, 228, 180, 110, 208, 139, 229, 146, 24, 231, 118, 175, 180, 55, 191, 37, 150, 61} 124 | outputbytes := []byte{0, 91, 50, 25, 214, 94, 119, 36, 71, 216, 33, 152, 85, 184, 34, 120, 61, 161, 164, 223, 76, 53, 40, 246, 76, 38, 235, 204, 43, 31, 179, 28} 125 | input := r255.NewElement() 126 | err = input.Decode(inputbytes) 127 | require.NoError(t, err) 128 | 129 | output := r255.NewElement() 130 | err = output.Decode(outputbytes) 131 | require.NoError(t, err) 132 | 133 | inout := &VrfInOut{ 134 | input: input, 135 | output: output, 136 | } 137 | 138 | cbytes := []byte{120, 23, 235, 159, 115, 122, 207, 206, 123, 232, 75, 243, 115, 255, 131, 181, 219, 241, 200, 206, 21, 22, 238, 16, 68, 49, 86, 99, 76, 139, 39, 0} 139 | sbytes := []byte{102, 106, 181, 136, 97, 141, 187, 1, 234, 183, 241, 28, 27, 229, 133, 8, 32, 246, 245, 206, 199, 142, 134, 124, 226, 217, 95, 30, 176, 246, 5, 3} 140 | c := r255.NewScalar() 141 | err = c.Decode(cbytes) 142 | require.NoError(t, err) 143 | 144 | s := r255.NewScalar() 145 | err = s.Decode(sbytes) 146 | require.NoError(t, err) 147 | 148 | proof := &VrfProof{ 149 | c: c, 150 | s: s, 151 | } 152 | 153 | ok, err := pub.VrfVerify(transcript, inout.Output(), proof) 154 | require.NoError(t, err) 155 | require.True(t, ok) 156 | } 157 | 158 | // input data from https://github.com/noot/schnorrkel/blob/master/src/vrf.rs#L922 159 | func TestVrfInOut_MakeBytes(t *testing.T) { 160 | transcript := NewSigningContext([]byte("yo!"), []byte("meow")) 161 | 162 | pub := [32]byte{12, 132, 183, 11, 234, 190, 96, 172, 111, 239, 163, 137, 148, 163, 69, 79, 230, 61, 134, 41, 69, 90, 134, 229, 132, 128, 6, 63, 139, 220, 202, 0} 163 | input := []byte{188, 162, 182, 161, 195, 26, 55, 223, 166, 205, 136, 92, 211, 130, 184, 194, 183, 81, 215, 192, 168, 12, 39, 55, 218, 165, 8, 105, 155, 73, 128, 68} 164 | output := [32]byte{214, 40, 153, 246, 88, 74, 127, 242, 54, 193, 7, 5, 90, 51, 45, 5, 207, 59, 64, 68, 134, 232, 19, 223, 249, 88, 74, 125, 64, 74, 220, 48} 165 | proof := [64]byte{144, 199, 179, 5, 250, 199, 220, 177, 12, 220, 242, 196, 168, 237, 106, 3, 62, 195, 74, 127, 134, 107, 137, 91, 165, 104, 223, 244, 3, 4, 141, 10, 129, 54, 134, 31, 49, 250, 205, 203, 254, 142, 87, 123, 216, 108, 190, 112, 204, 204, 188, 30, 84, 36, 247, 217, 59, 125, 45, 56, 112, 195, 84, 15} 166 | makeBytes16Expected := []byte{169, 57, 149, 50, 0, 243, 120, 138, 25, 250, 74, 235, 247, 137, 228, 40} 167 | 168 | pubkey, err := NewPublicKey(pub) 169 | require.NoError(t, err) 170 | 171 | out := new(VrfOutput) 172 | err = out.Decode(output) 173 | require.NoError(t, err) 174 | 175 | inout, err := out.AttachInput(pubkey, transcript) 176 | require.NoError(t, err) 177 | require.Equal(t, input, inout.input.Encode([]byte{})) 178 | 179 | p := new(VrfProof) 180 | err = p.Decode(proof) 181 | require.NoError(t, err) 182 | 183 | verifyTranscript := NewSigningContext([]byte("yo!"), []byte("meow")) 184 | ok, err := pubkey.VrfVerify(verifyTranscript, out, p) 185 | require.NoError(t, err) 186 | require.True(t, ok) 187 | 188 | bytes, err := inout.MakeBytes(16, []byte("substrate-babe-vrf")) 189 | require.NoError(t, err) 190 | require.Equal(t, makeBytes16Expected, bytes) 191 | } 192 | 193 | func TestVrfVerify_NotKusama(t *testing.T) { 194 | kusamaVRF = false 195 | defer func() { 196 | kusamaVRF = true 197 | }() 198 | 199 | transcript := NewSigningContext([]byte("yo!"), []byte("meow")) 200 | pub := [32]byte{178, 10, 148, 176, 134, 205, 129, 139, 45, 90, 42, 14, 71, 116, 227, 233, 15, 253, 56, 53, 123, 7, 89, 240, 129, 61, 83, 213, 88, 73, 45, 111} 201 | input := []byte{118, 192, 145, 134, 145, 226, 209, 28, 62, 15, 187, 236, 43, 229, 255, 161, 72, 122, 128, 21, 28, 155, 72, 19, 67, 100, 50, 217, 72, 35, 95, 111} 202 | output := [32]byte{114, 173, 188, 116, 143, 11, 157, 244, 87, 214, 231, 0, 234, 34, 157, 145, 62, 154, 68, 161, 121, 66, 49, 25, 123, 38, 138, 20, 207, 105, 7, 5} 203 | proof := [64]byte{123, 219, 60, 236, 49, 106, 113, 229, 135, 98, 153, 252, 10, 63, 65, 174, 242, 191, 130, 65, 119, 177, 227, 15, 103, 219, 192, 100, 174, 204, 136, 3, 95, 148, 246, 105, 108, 51, 20, 173, 123, 108, 5, 49, 253, 21, 170, 41, 214, 1, 141, 97, 93, 182, 52, 175, 202, 186, 149, 213, 69, 57, 7, 14} 204 | make_bytes_16_expected := []byte{193, 153, 104, 18, 4, 27, 121, 146, 149, 228, 12, 17, 251, 184, 117, 16} 205 | 206 | pubkey, err := NewPublicKey(pub) 207 | require.NoError(t, err) 208 | 209 | out := new(VrfOutput) 210 | err = out.Decode(output) 211 | require.NoError(t, err) 212 | 213 | inout, err := out.AttachInput(pubkey, transcript) 214 | require.NoError(t, err) 215 | require.Equal(t, input, inout.input.Encode([]byte{})) 216 | 217 | p := new(VrfProof) 218 | err = p.Decode(proof) 219 | require.NoError(t, err) 220 | 221 | verifyTranscript := NewSigningContext([]byte("yo!"), []byte("meow")) 222 | ok, err := pubkey.VrfVerify(verifyTranscript, out, p) 223 | require.NoError(t, err) 224 | require.True(t, ok) 225 | 226 | bytes, err := inout.MakeBytes(16, []byte("substrate-babe-vrf")) 227 | require.NoError(t, err) 228 | require.Equal(t, make_bytes_16_expected, bytes) 229 | } 230 | 231 | func TestVRFVerify_PublicKeyAtInfinity(t *testing.T) { 232 | signTranscript := merlin.NewTranscript("vrf-test") 233 | verifyTranscript := merlin.NewTranscript("vrf-test") 234 | 235 | priv := SecretKey{} 236 | pub, err := priv.Public() 237 | require.NoError(t, err) 238 | require.Equal(t, pub.key, publicKeyAtInfinity) 239 | inout, proof, err := priv.VrfSign(signTranscript) 240 | require.NoError(t, err) 241 | 242 | _, err = pub.VrfVerify(verifyTranscript, inout.Output(), proof) 243 | require.ErrorIs(t, err, ErrPublicKeyAtInfinity) 244 | } 245 | --------------------------------------------------------------------------------