Coder Social home page Coder Social logo

gigabitcoin / secp256k1.swift Goto Github PK

View Code? Open in Web Editor NEW
96.0 7.0 53.0 556 KB

Elliptic Curve, Schnorr, and ZKP for Bitcoin. Supports iOS macOS tvOS watchOS visionOS + Linux.

License: MIT License

Swift 97.18% Dockerfile 0.38% C 2.44%
taproot xcode secp256k1 swift schnorr bitcoin ecdsa ecdh library c

secp256k1.swift's People

Contributors

charlie632 avatar csjones avatar davidscheutz avatar dependabot[bot] avatar finestructure avatar nakajima avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

secp256k1.swift's Issues

Cannot install package via SPM when importing it from another package

This one is a weird one. I've been using this library in an App with no problems at all. But when I tried to create a package for the functions I've been working on, I got this error:

product 'secp256k1' required by package 'ecies' target 'ecies' not found.

This is my Package.swift

// swift-tools-version: 5.8
// The swift-tools-version declares the minimum version of Swift required to build this package.

import PackageDescription

let package = Package(
    name: "ecies",
    products: [
        .library(
            name: "ecies",
            targets: ["ecies"]),
    ],
    dependencies: [
        .package( url: "https://github.com/GigaBitcoin/secp256k1.swift.git", from: "0.12.0")
    ],
    targets: [
        // Targets are the basic building blocks of a package. A target can define a module or a test suite.
        // Targets can depend on other targets in this package, and on products in packages this package depends on.
        .target(
            name: "ecies",
            dependencies: ["secp256k1"]),
        .testTarget(
            name: "eciesTests",
            dependencies: ["ecies"]),
    ]
)

This is just the skeleton of the package, there's no actual code whatsoever.

It also throws an error whenever I try to import it:

image

Any clues?

Add support for VisionOS

Im not exactly sure how hard this would be, but curious if adding support for VisionOS platform would be possible?

Of course I can use VisionOS (Made for iPad) target, but you lose the native look and feel of the platform by doing so.

Code example of signing using hashed message?

I've read that it seems to be possible to sign an already hashed message in here and here

Though I can't figure out how to sign a SHA3 256 message using the library. So far I've hashed my message with SHA3 256 via CryptoSwift. An example snippet on how to do the signing would be appreciated.

Thanks.

BitcoinSign Transaction

Hi all!
Is it possible to sign BitcoinInput received from backend in hex format with this library?

Thanks a lot!

xcodebuild fails for 0.13.0

xcodebuild fails after updating package from 0.12.2 to 0.13.0.

Screenshot 2023-09-20 at 11 30 24

Should be reproducible with the following github workflow snippet:

jobs:
  build:
    runs-on: macOS-latest
    strategy:
      matrix:
        platform:
          - iOS
    steps:
      - uses: actions/[email protected]
      - uses: mxcl/xcodebuild@v1
        with:
          platform: ${{ matrix.platform }}
          action: test
          scheme: <INSERT SCHEME NAME HERE>
          code-coverage: true
          upload-logs: always

library release on cocoapods?

Do you plan to release the lib on cocoapods or to add a .podspec file in the repo.
I'm working on react native so I don't have access to swfit package manager, only to pods

nvm I need the podspec for this, i'm so sorry...

Well, the thing is that i need to use this package with the template created by this npx create-react-native-library@latest react-native-awesome-library
This gives me a basic podspec file in which i can add other pods dependencies, in this case i would add your zkp_bindings
I can't use the xcodebuild for that, the only possible way is to build the package with the podspec and i cannot import a spm thing inside the podspec.
I'm getting quite desperate right here

objc

hello. is it possible to use this within an objc application?

Can't use with SPM

Doesn't seem to work:
commit: a2d14eceeefa54f68a646397da5e7090edae0dea
error: Missing required module 'secp256k1_bindings'

能否给一个运行结果

import secp256k1

// Private key
let privateBytes = try! "14E4A74438858920D8A35FB2D88677580B6A2EE9BE4E711AE34EC6B396D87B5C".bytes
let privateKey = try! secp256k1.Signing.PrivateKey(rawRepresentation: privateBytes)

// Public key
print(String(byteArray: privateKey.publicKey.rawRepresentation))

// ECDSA
let messageData = "We're all Satoshi.".data(using: .utf8)!
let signature = try! privateKey.ecdsa.signature(for: messageData)

// DER signature
print(try! signature.derRepresentation.base64EncodedString())

Taproot address format

Hey bro, Im excited about using your lib to generate Taproot address and It did work for my case.

But as I reading Vectors from bip86 https://github.com/bitcoin/bips/blob/master/bip-0086.mediawiki I found that the output address is not equal to the expected one, could you help to advice?

mnemonic = abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about
rootpriv = xprv9s21ZrQH143K3GJpoapnV8SFfukcVBSfeCficPSGfubmSFDxo1kuHnLisriDvSnRRuL2Qrg5ggqHKNVpxR86QEC8w35uxmGoggxtQTPvfUu
rootpub  = xpub661MyMwAqRbcFkPHucMnrGNzDwb6teAX1RbKQmqtEF8kK3Z7LZ59qafCjB9eCRLiTVG3uxBxgKvRgbubRhqSKXnGGb1aoaqLrpMBDrVxga8

// Account 0, root = m/86'/0'/0'
xprv = xprv9xgqHN7yz9MwCkxsBPN5qetuNdQSUttZNKw1dcYTV4mkaAFiBVGQziHs3NRSWMkCzvgjEe3n9xV8oYywvM8at9yRqyaZVz6TYYhX98VjsUk
xpub = xpub6BgBgsespWvERF3LHQu6CnqdvfEvtMcQjYrcRzx53QJjSxarj2afYWcLteoGVky7D3UKDP9QyrLprQ3VCECoY49yfdDEHGCtMMj92pReUsQ

// Account 0, first receiving address = m/86'/0'/0'/0/0
xprv         = xprvA449goEeU9okwCzzZaxiy475EQGQzBkc65su82nXEvcwzfSskb2hAt2WymrjyRL6kpbVTGL3cKtp9herYXSjjQ1j4stsXXiRF7kXkCacK3T
xpub         = xpub6H3W6JmYJXN49h5TfcVjLC3onS6uPeUTTJoVvRC8oG9vsTn2J8LwigLzq5tHbrwAzH9DGo6ThGUdWsqce8dGfwHVBxSbixjDADGGdzF7t2B
internal_key = cc8a4bc64d897bddc5fbc2f670f7a8ba0b386779106cf1223c6fc5d7cd6fc115
output_key   = a60869f0dbcf1dc659c9cecbaf8050135ea9e8cdc487053f1dc6880949dc684c
scriptPubKey = 5120a60869f0dbcf1dc659c9cecbaf8050135ea9e8cdc487053f1dc6880949dc684c
address      = bc1p5cyxnuxmeuwuvkwfem96lqzszd02n6xdcjrs20cac6yqjjwudpxqkedrcr

My output is bc1qxr25l5xagg9xuhudxcj0tu6g9jhr2rme6hc82wl4hmhectv34u7qpnecln

Is it possible to generate an invalid PrivateKey when no secret it passed?

If I don't pass a secret to secp256k1.Signing.PrivateKey I get a random one. Checking the code to see its implementation, I see that it may be possible to generate an invalid key?

https://github.com/GigaBitcoin/secp256k1.swift/blob/a69bc11b381207c1a774b8f1fb0de6e30c4f6490/Sources/zkp/secp256k1.swift#L154C1-L154C1

This will calculate a safe random number of 32 bytes, but I believe a couple of values may be invalid (see https://crypto.stackexchange.com/a/30272).

Not sure if down the line there are some checks to check the validity of this value or if when generating the PublicKey (in the same constructor) it will throw an error due to this reason.

Why my web app and ios app gets different shared secret?

Hello! I have already working web app that uses https://github.com/bitchan/eccrypto and iOS app that uses this package. Once we try to make shared key we have different results for some reason, can you please help me?

private key: c549948162ebcbee0d2d0905c441dafb2af2f0b64394adeca8a29de73d0f4aa7
public key: 042cffd828be7b06776524c860e13b5991758102ee8029bc402644220ad82adfb2bcb6d6d3a287e1abe327e887a294bd9446e5c47048a8508385181cfd1f169acf

in web app shared key: 4c9c90c735a3a58ce168f260e5ad18eb1b3d7289ab12250184c31d78679b1d15
in ios app shared key: ae9112702a3cd4f9dc2b8e48a6f39f6c0e537c6632fa107f8dda6870a42f372d

As i see both libs are using original C files to make secp256k1, but for some reason we have different results.

Recovery of pubic key when manually building signature

Hey @csjones, I'm encountering this error when trying to recover a public key:

Fatal error: 'try!' expression unexpectedly raised an error: secp256k1.secp256k1Error.underlyingCryptoError

Steps to reproduce:

        let sigHex = "283f5723bc367993c7492f8d79087b499e776012e0d744426e1be8e12d57264ab765f52dad6dac7df61d2209e875b037390c181b8c205ad47443c5bfea2f08c149"
        let dataHex = "03a69666f5863ecc3b35ac143ef843f2a07ef98a76c09fba6bbd23ea36c7839602"
        
        let sigData = Data(try! sigHex.bytes)
        let data = Data(try! dataHex.bytes)
        
        let sig = try! secp256k1.Recovery.ECDSASignature(dataRepresentation: sigData)
        
        let publicKey = try! secp256k1.Recovery.PublicKey(data, signature: sig)

I've dug around the library's source but I can't seem to resolve or figure out what I'm doing wrong. Is this a bug?

Contructing a PublicKey with rawRepresentation fails with incorrect size

I'm trying to construct a secp256k1.Signing.PublicKey with a hex encoded string.
This is my code -

let pubkeyHex = "11cc106e72c654b64bb037d0ccbe2ff47187fa5bb77330dd70398c2cb051fbd6"
let pubKey = try secp256k1.Signing.PublicKey(rawRepresentation: pubkeyHex.bytes, format: .compressed)

I get a an error with incorrectKeySize.
I can see that my pubkeyHex.bytes.count is 32 and not 33. Do I need to pad my hexstring ?
Any pointers?


version - 0.8.1

value of type `secp256k1_surjectionproof` has no member `data`

hi guys!
I'm trying to use this struct https://github.com/ElementsProject/secp256k1-zkp/blob/d22774e248c703a191049b78f8d04f37d6fcfa05/include/secp256k1_surjectionproof.h#L42-L53 in my swift code.
When i try accessing the .data field i get this compilation error.
From what i can understand it is something reguarding the length of the array. If i try to modify the length of the array to something smaller is now recognised. but clearly i need the real length of the array that should be something around 8000 bytes.
Do you know what to do about this?

Please use semver for release tags

Swift Package Manager expects SemVer versioning.

https://developer.apple.com/documentation/xcode/publishing-a-swift-package-with-xcode#Tag-your-latest-commit

Currently there are a number of breaking changes in previously released versions which is making it very difficult to find compatible versions of this library between different libraries using this one as a dependency. This is due to .exact() being used instead of from: for this library to avoid the breaking changes.

If you look at 0.10.0, there is a breaking change at 0.12.1, thereafter there is another breaking change leading up to 0.15.0.

Can I get Public Key from Private key with length 65 bits?

I have such private key: 703d3b63e84421e59f9359f8b27c25365df9d85b6b1566e3168412fa599c12f4,
using pub1 = priv1!.publicKey I'm getting public key like this: 02c9c68596824505dd6cd1993a16452b4b1a13bacde56f80e9049fd03850cce137

But as I understand I should have key like this: 04c9c68596824505dd6cd1993a16452b4b1a13bacde56f80e9049fd03850cce137c1fa4acb7bef7edcc04f4fa29e071ea17e34fa07fa5d87b5ebf6340df6558498

Can you explain please why I'm getting another key?

signature using the already hashed hex string value

Hello, is there a way to use this package to get the signature of an already hashed hex string value? From what I can tell, it uses data that still needs to be hashed. I like the simplicity of this package compared to others, I just need to get past this one issue :(

Example usage

Do you have any examples of how you would sign a taproot input using this library?

How to create PrivateKey by importing pem private key?

For example, a private key string of this form:

-----BEGIN PRIVATE KEY-----
MIGTAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBHkwdwIBAQQgeeKPvGwZ92ghbN4+
bReH21oDBQnD1f0/HOs8usdsdSDuouioi77DSY9sdsa9dya89d8s/aDrJxITXeXo
/QFWM+SKDJLdfsfw4A546Jsdf/ipgevqznDVKTDJxoOK6DliXS20GQjZZ9T6xx3D
ZqoY65zp
-----END PRIVATE KEY-----

Differenct signature result with other libraries

I am using the sample code to test:

let privateBytes = try! "14E4A74438858920D8A35FB2D88677580B6A2EE9BE4E711AE34EC6B396D87B5C".bytes
let privateKey = try! secp256k1.Signing.PrivateKey(rawRepresentation: privateBytes)
print("private key: \(String(bytes: privateKey.rawRepresentation))")
print("public key: \(String(bytes: privateKey.publicKey.rawRepresentation))")
// ECDSA
let str = "We're all Satoshi."
let messageData = str.data(using: .utf8)!
let signature = try! privateKey.ecdsa.signature(for: messageData)
print("signature: \(String(bytes: signature.rawRepresentation))")

the results are:

private key: 14e4a74438858920d8a35fb2d88677580b6a2ee9be4e711ae34ec6b396d87b5c
public key: 02734b3511150a60fc8cac329cd5ff804555728740f2f2e98bc4242135ef5d5e4e
signature: 09b7cc8f9c570c6cec33e926615879c7b4ad0dbdfed2180d893f0de50d31063e1201f0847ea4b43c4e3f13955a19a53f52a9a7eddaec3368efa2a45d172bf456

When I put the same private key and message to the other libraries, the values are not the same, you can test on the website: https://paulmillr.com/noble/

image

Cannot add package as dependency SPM

I want to add secp256k1 SPM package as dependency but getting an error in HDWallet files:
No such module 'secp256k1'
here is my package.swift

    name: "HDWallet",
    products: [
        // Products define the executables and libraries a package produces, and make them visible to other packages.
        .library(
            name: "HDWallet",
            targets: ["HDWallet"]),
    ],
    dependencies: [
        .package(url: "https://github.com/krzyzanowskim/CryptoSwift", from: "1.0.0"),
        .package(
            name: "secp256k1",
            url: "https://github.com/GigaBitcoin/secp256k1.swift.git",
            from: "0.3.0"
        )
    ],
    targets: [
        // Targets are the basic building blocks of a package. A target can define a module or a test suite.
        // Targets can depend on other targets in this package, and on products in packages this package depends on.
        .target(
            name: "HDWallet",
            dependencies: ["CryptoSwift",
                           "secp256k1"],
            path: "HDWalletKit"),
        .testTarget(
            name: "HDWalletTests",
            dependencies: ["HDWallet"]),
    ]
)```

How to use secp256k1_ec_pubkey_combine

How to use secp256k1_ec_pubkey_combine ?
I'd like to use this function from secp256k1
But there is no interface from this library.
Would you like to show that how to use it?
Thank you.

Is there really a random k injected when calculating an ECDSA signature ?

I have launched several times the example code on 0.10.0 and check the signature :

let privateBytes = try! "14E4A74438858920D8A35FB2D88677580B6A2EE9BE4E711AE34EC6B396D87B5C".bytes
let privateKey = try! secp256k1.Signing.PrivateKey(rawRepresentation: privateBytes)
let messageData = "We're all Satoshi.".data(using: .utf8)!
let signature = try! privateKey.ecdsa.signature(for: messageData)
print(try! signature.derRepresentation.base64EncodedString())

When I check the signature DER output, I always see the same value for each pass(something which doesn't happen with schnorr signatures), which means that the signature generation is completely deterministic and there is no randomness injected.
I was certain that it was mandatory to input a random k or else the signature is easily crackable : https://en.wikipedia.org/wiki/Elliptic_Curve_Digital_Signature_Algorithm#Security

Since I am not an expert in cryptography, I don't know if it's by design, if it has been changed in recent versions or if I misunderstood the algorithm requirements.
I wanted to be assured it doesn't threaten the security of the signature.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.