21-DOT-DEV / swift-secp256k1

Elliptic Curve, Schnorr, and ZKP for Bitcoin. Supports iOS macOS tvOS watchOS visionOS + Linux.
MIT License
107 stars 53 forks source link

Did library already support sign a taproot input? #356

Closed JackKuo1219 closed 1 year ago

JackKuo1219 commented 1 year ago

Did the library already support signing a taproot input? Could you provide some examples?

csjones commented 1 year ago

Hey @JackKuo1219 👋

Yes, this package supports signing taproot inputs. You'll want to use Schnorr signatures to achieve this and, generally, it will look something like this:

// BIP340 enables Taproot via Schnorr signatures
let privateKey = try! secp256k1.Schnorr.PrivateKey()

// Create a Taproot input
var taprootInput = try! "8B3BCDF190DDA9805AAB5C7333049D0A".bytes

// Get the Schnorr signature for the Taproot input
let signature = try! privateKey.signature(for: messageDigest)

If you can provide more context to a specific example with a taproot input you want to sign, I'll try to create a better example. 🙂

JackKuo1219 commented 1 year ago

Hi @csjones Thanks for your reply. And could you let us know what should we need when generating a taproot address?

csjones commented 1 year ago

Hey @JackKuo1219

Generating a Taproot address is two things, get the x-only key and encoding it with bech32m

// Create private key
let privateKey = try! secp256k1.Schnorr.PrivateKey()

// Get the x-only key
let xonlyKey = privateKey.xonly

// Encode the x-only key using bech32m
let taprootAddress = /* bech32m-encode f128a8a8a636e19f00a80169550fedfc26b6f5dd04d935ec452894aad938ef0c */

print(taprootAddress) // bc1p7y52329xxmse7q9gq9542rldlsntdawaqnvntmz99z224kfcauxqag4w9y

Notice this package does not provide any bech32 encoding but there are open source Swift packages that do offer this functionality.

csjones commented 1 year ago

Hey @JackKuo1219

Closing this issue. Feel free to open another issue if unresolved. Check out this thread too https://github.com/GigaBitcoin/secp256k1.swift/issues/361, it could also be helpful.