blinklabs-io / bursa

Programmatic Cardano Wallet
Apache License 2.0
5 stars 2 forks source link

Support for parsing key files #81

Open wolf31o2 opened 6 months ago

wolf31o2 commented 6 months ago

We should have functions which can parse the key file data.

agaffney commented 5 months ago

Copied from #83 (mostly for the code rather than the explanation around it):

it generates valid keys, but they just differ from how the cli would interpret things.

func decodeNonExtendedCborKey(skeyBytes []byte) ([]byte, []byte, error) {
    // Example SKEY format:
    // 5820{32 bytes that serve as a seed for ed25519}
    // This generates a key pair, which is the private and public keys concatenated
    // Then, Apollo just uses this raw to sign with ed25519, which expects the ed25519 key from this seed
    if len(skeyBytes) != 34 {
        return nil, nil, errors.New("invalid cbor skey hex length")
    }
    if skeyBytes[0] != 0x58 || skeyBytes[1] != 0x20 {
        return nil, nil, errors.New("invalid cbor skey hex prefix")
    }
    key := ed25519.NewKeyFromSeed(skeyBytes[2:])

    return key[:], key[32:], nil
}

Here's the implementation that ended up working; from the skey bytes (5820xyz), we grab the juicy bits (strip off the 5820), and then pass that to ed25519.NewKeyFromSeed to get the actual payment key. This is what then works with the ed25519.Sign / ed25519.Verify method.

However in bursa, https://github.com/blinklabs-io/bursa/blob/main/bursa.go#L134-L144, it looks like you're just taking the key (not the seed), and serializing it. The fivebinaries bip32 library doesn't actually have code that can correctly handle non-extended keys that could be found, resulting in having to mix the bip32 and ed25519 go libraries

Here's the code that produces results consistent with cardano-cli for both extended and non-extended keys:

type KeyPair struct {
    vkey []byte
    skey []byte
}

func decodeExtendedCborKey(skeyBytes []byte) ([]byte, []byte, error) {
    // Example SKEY format:
    // 5880{64 bytes of extended private key}{32 bytes of public key}{32 bytes of chain code}
    // Apollo (our transaction builder) checks the key size; if it's an extended key,
        // it constructs a fivebinaries.bip32.XPrv from it, and uses the Sign method on that type.
    if len(skeyBytes) != 130 {
        return nil, nil, errors.New("invalid cbor skey hex length")
    }
    if skeyBytes[0] != 0x58 || skeyBytes[1] != 0x80 {
        return nil, nil, errors.New("invalid cbor skey hex prefix")
    }
    return skeyBytes[2:98], skeyBytes[66:98], nil
}

func decodeNonExtendedCborKey(skeyBytes []byte) ([]byte, []byte, error) {
    // Example SKEY format:
    // 5820{32 bytes that serve as a seed for ed25519}
    // This generates a key pair, which is the private and public keys concatenated
    // Apollo, checks the key length for how to sign txs
        // If the length is 64 bytes, it just uses the `skeyBytes` directly against
        // the ed25519.Sign method
    if len(skeyBytes) != 34 {
        return nil, nil, errors.New("invalid cbor skey hex length")
    }
    if skeyBytes[0] != 0x58 || skeyBytes[1] != 0x20 {
        return nil, nil, errors.New("invalid cbor skey hex prefix")
    }
    key := ed25519.NewKeyFromSeed(skeyBytes[2:])

    return key[:], key[32:], nil
}

// Example skey file
//
//    {
//       "type": "PaymentSigningKeyShelley_ed25519",
//       "description": "Payment Signing Key",
//       "cborHex": "58200000000000000000000000000000000000000000000000000000000000000000"
//    }
func decodeKeyEnvelope(fileBytes []byte) ([]byte, []byte, error) {
    type keyEnvelope struct {
        Type    string `json:"type"`
        CborHex string `json:"cborHex"`
    }
    var env keyEnvelope
    err := json.Unmarshal(fileBytes, &env)
    if err != nil {
        return nil, nil, errors.New("could not parse key file envelope")
    }
    cbor, err := hex.DecodeString(env.CborHex)
    if err != nil {
        return nil, nil, fmt.Errorf("could not decode key from hex: %w", err)
    }
    switch env.Type {
    case "PaymentSigningKeyShelley_ed25519":
        return decodeNonExtendedCborKey(cbor)
    case "PaymentExtendedSigningKeyShelley_ed25519_bip32":
        return decodeExtendedCborKey(cbor)
    }
    return nil, nil, errors.New("unknown key type")
}

func getKeyPair(wallet dextype.Wallet) (*KeyPair, error) {
    skeyFileBytes, err := os.ReadFile(wallet.SkeyFile)
    if err != nil {
        return nil, fmt.Errorf("couldn't read skey file %v: %w", wallet.SkeyFile, err)
    }
    sk, pub, err := decodeKeyEnvelope(skeyFileBytes)
    if err != nil {
        return nil, fmt.Errorf("couldn't decode skey file %v: %w", wallet.SkeyFile, err)
    }
    return &KeyPair{
        skey: sk,
        vkey: pub,
    }, nil

}

And here's the unit tests written to track this down:

const extendedKey = "588098ff8a19665b345c4cef5dbbf5db492186556e756004c080a90965410ebbff5fddcd8085c1a64c5398c7617366f213ff0e82a40d796b33657a4396588f572df114195ad024582c605ea389fd4e53b2ac2400b19525d5291b287a82b9d0ca5f939f0fcdb379ac499cad850023212ae43ee1edc310513580394df05beb4d461701"
const signingKey = "5820c7eac5993be47d08898ba263e76aff0bbfdb0eb81a17b5d5474f658f299fccc4"

func Test_SigningKey(t *testing.T) {

    skey, _ := hex.DecodeString(signingKey)

    key, pk, err := decodeNonExtendedCborKey(skey)
    assert.Nil(t, err)
    fmt.Printf("%v\n", hex.EncodeToString(key[:]))

    txId, _ := hex.DecodeString("ee3d1301ec86080e8f9ebbd388586fc2dbb4d809853d103ae7a1e2420e5d775a")

    expectedSig, _ := hex.DecodeString("b6fee62653cb2456f0d90282260385050d60063b48c63803d86cfb2e4bb8e3ff7425894e075b56b7bc82c5233853c9bc7b95c5a792d220df8ebd839ea3752b06")
    expectedSecretKey, _ := hex.DecodeString("c7eac5993be47d08898ba263e76aff0bbfdb0eb81a17b5d5474f658f299fccc4574a5b38a81dec91b45df4d95bc98600ee27c1f562c295c491062e5afe1634a1")
    expectedPubKey, _ := hex.DecodeString("574a5b38a81dec91b45df4d95bc98600ee27c1f562c295c491062e5afe1634a1")
    expectedPubKeyHash, _ := hex.DecodeString("6b495d5fdb64951f80ffe9d20542c8508c080c667c1b089b0a7c8ad5")

    sig := ed25519.Sign(key, txId)

    assert.Equal(t, expectedSecretKey, []byte(key[:]))
    assert.Equal(t, expectedPubKey, []byte(pk[:]))
    assert.Equal(t, expectedSig, sig)

    apollob := apollo.New(nil)
    apollob = apollob.
        SetWalletFromKeypair(hex.EncodeToString(pk[:]), hex.EncodeToString(key), constants.MAINNET).
        SetWalletAsChangeAddress()
    pkhApollo := apollob.GetWallet().GetAddress().PaymentPart
    assert.Equal(t, expectedPubKeyHash, pkhApollo[:])
    sigApollo := apollob.GetWallet().(*apollotypes.GenericWallet).SigningKey.Sign(txId)
    assert.Equal(t, expectedSig, sigApollo)
}

func Test_ExtendedSigningKey(t *testing.T) {
    skey, _ := hex.DecodeString(extendedKey)
    key, pub, err := decodeExtendedCborKey(skey)
    assert.Nil(t, err)

    txId, _ := hex.DecodeString("ee3d1301ec86080e8f9ebbd388586fc2dbb4d809853d103ae7a1e2420e5d775a")

    fmt.Printf("%x\n", key)
    expectedSig, _ := hex.DecodeString("63e781ea55e69f3bdb36b904186e7404cdd878bc4b99452c379a64bba2fe2a5265fa5fe7be249ec910d7046a8bbde29a6dd86c0558d73c6122efd1b6b34dfd0d")
    expectedSecretKey, _ := hex.DecodeString("98ff8a19665b345c4cef5dbbf5db492186556e756004c080a90965410ebbff5fddcd8085c1a64c5398c7617366f213ff0e82a40d796b33657a4396588f572df114195ad024582c605ea389fd4e53b2ac2400b19525d5291b287a82b9d0ca5f93")
    expectedPubKey, _ := hex.DecodeString("14195ad024582c605ea389fd4e53b2ac2400b19525d5291b287a82b9d0ca5f93")
    expectedPubKeyHash, _ := hex.DecodeString("441f2932b0ac8e37829f6599d69dedb39c56bd678a9fa7c11fdc1517")

    assert.Equal(t, expectedSecretKey, []byte(key[:]))
    assert.Equal(t, expectedPubKey, []byte(pub[:]))
    apollob := apollo.New(nil)

    apollob = apollob.
        SetWalletFromKeypair(hex.EncodeToString(pub), hex.EncodeToString(key), constants.MAINNET).
        SetWalletAsChangeAddress()
    pkhApollo := apollob.GetWallet().GetAddress().PaymentPart
    assert.Equal(t, expectedPubKeyHash, pkhApollo[:])
    sigApollo := apollob.GetWallet().(*apollotypes.GenericWallet).SigningKey.Sign(txId)
    assert.True(t, ed25519.Verify(ed25519.PublicKey(pub[:]), txId, sigApollo))
    assert.Equal(t, expectedSig, sigApollo)
}