本文整理汇总了Golang中github.com/btcsuite/btcd/btcec.NewPrivateKey函数的典型用法代码示例。如果您正苦于以下问题:Golang NewPrivateKey函数的具体用法?Golang NewPrivateKey怎么用?Golang NewPrivateKey使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了NewPrivateKey函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: GenerateKey
func GenerateKey() Secret {
keys, _ := btcec.NewPrivateKey(btcec.S256())
pub := keys.PubKey().SerializeCompressed()
priv := keys.Serialize()
sin := GenerateSin(pub)
return Secret{pub, priv, sin}
}
示例2: testKeyGeneration
func testKeyGeneration(t *testing.T, c *btcec.KoblitzCurve, tag string) {
priv, err := btcec.NewPrivateKey(c)
if err != nil {
t.Errorf("%s: error: %s", tag, err)
return
}
if !c.IsOnCurve(priv.PublicKey.X, priv.PublicKey.Y) {
t.Errorf("%s: public key invalid: %s", tag, err)
}
}
示例3: TestGenerateSharedSecret
func TestGenerateSharedSecret(t *testing.T) {
privKey1, err := btcec.NewPrivateKey(btcec.S256())
if err != nil {
t.Errorf("private key generation error: %s", err)
return
}
privKey2, err := btcec.NewPrivateKey(btcec.S256())
if err != nil {
t.Errorf("private key generation error: %s", err)
return
}
secret1 := btcec.GenerateSharedSecret(privKey1, privKey2.PubKey())
secret2 := btcec.GenerateSharedSecret(privKey2, privKey1.PubKey())
if !bytes.Equal(secret1, secret2) {
t.Errorf("ECDH failed, secrets mismatch - first: %x, second: %x",
secret1, secret2)
}
}
示例4: generateKeyPair
func generateKeyPair() (*btcec.PublicKey, *btcec.PrivateKey) {
// Generate a private key, use the curve secpc256k1 and kill the program on
// any errors
priv, err := btcec.NewPrivateKey(btcec.S256())
if err != nil {
// There was an error. Log it and bail out
log.Fatal(err)
}
return priv.PubKey(), priv
}
示例5: testSignCompact
func testSignCompact(t *testing.T, tag string, curve *btcec.KoblitzCurve,
data []byte, isCompressed bool) {
tmp, _ := btcec.NewPrivateKey(curve)
priv := (*btcec.PrivateKey)(tmp)
hashed := []byte("testing")
sig, err := btcec.SignCompact(curve, priv, hashed, isCompressed)
if err != nil {
t.Errorf("%s: error signing: %s", tag, err)
return
}
pk, wasCompressed, err := btcec.RecoverCompact(curve, sig, hashed)
if err != nil {
t.Errorf("%s: error recovering: %s", tag, err)
return
}
if pk.X.Cmp(priv.X) != 0 || pk.Y.Cmp(priv.Y) != 0 {
t.Errorf("%s: recovered pubkey doesn't match original "+
"(%v,%v) vs (%v,%v) ", tag, pk.X, pk.Y, priv.X, priv.Y)
return
}
if wasCompressed != isCompressed {
t.Errorf("%s: recovered pubkey doesn't match compressed state "+
"(%v vs %v)", tag, isCompressed, wasCompressed)
return
}
// If we change the compressed bit we should get the same key back,
// but the compressed flag should be reversed.
if isCompressed {
sig[0] -= 4
} else {
sig[0] += 4
}
pk, wasCompressed, err = btcec.RecoverCompact(curve, sig, hashed)
if err != nil {
t.Errorf("%s: error recovering (2): %s", tag, err)
return
}
if pk.X.Cmp(priv.X) != 0 || pk.Y.Cmp(priv.Y) != 0 {
t.Errorf("%s: recovered pubkey (2) doesn't match original "+
"(%v,%v) vs (%v,%v) ", tag, pk.X, pk.Y, priv.X, priv.Y)
return
}
if wasCompressed == isCompressed {
t.Errorf("%s: recovered pubkey doesn't match reversed "+
"compressed state (%v vs %v)", tag, isCompressed,
wasCompressed)
return
}
}
示例6: GenerateKeyPair
// GenerateKeyPair creates a random public/private key pair.
func GenerateKeyPair() (*SecretKey, *PublicKey, error) {
sk_s, err := btcec.NewPrivateKey(S256)
if err != nil {
return nil, nil, err
}
// Serialize the key pair
sk := newSecretKeyInt(sk_s.D)
pk := newPublicKeyCoords(sk_s.X, sk_s.Y)
sk_s.D.SetUint64(0)
return sk, pk, nil
}
示例7: GeneratePem
//All BitPay clients use a PEM file to store the private and public keys.
func GeneratePem() string {
priv, _ := btcec.NewPrivateKey(btcec.S256())
pub := priv.PubKey()
ecd := pub.ToECDSA()
oid := asn1.ObjectIdentifier{1, 3, 132, 0, 10}
curve := btcec.S256()
der, _ := asn1.Marshal(ecPrivateKey{
Version: 1,
PrivateKey: priv.D.Bytes(),
NamedCurveOID: oid,
PublicKey: asn1.BitString{Bytes: elliptic.Marshal(curve, ecd.X, ecd.Y)},
})
blck := pem.Block{Type: "EC PRIVATE KEY", Bytes: der}
pm := pem.EncodeToMemory(&blck)
return string(pm)
}
示例8: createCipherConn
// createCipherConn....
func (l *Listener) createCipherConn(lnConn *LNDConn) (*btcec.PrivateKey, error) {
var err error
var theirEphPubBytes []byte
// First, read and deserialize their ephemeral public key.
theirEphPubBytes, err = readClear(lnConn.Conn)
if err != nil {
return nil, err
}
if len(theirEphPubBytes) != 33 {
return nil, fmt.Errorf("Got invalid %d byte eph pubkey %x\n",
len(theirEphPubBytes), theirEphPubBytes)
}
theirEphPub, err := btcec.ParsePubKey(theirEphPubBytes, btcec.S256())
if err != nil {
return nil, err
}
// Once we've parsed and verified their key, generate, and send own
// ephemeral key pair for use within this session.
myEph, err := btcec.NewPrivateKey(btcec.S256())
if err != nil {
return nil, err
}
if _, err := writeClear(lnConn.Conn, myEph.PubKey().SerializeCompressed()); err != nil {
return nil, err
}
// Now that we have both keys, do non-interactive diffie with ephemeral
// pubkeys, sha256 for good luck.
sessionKey := fastsha256.Sum256(
btcec.GenerateSharedSecret(myEph, theirEphPub),
)
lnConn.chachaStream, err = chacha20poly1305.New(sessionKey[:])
// display private key for debug only
fmt.Printf("made session key %x\n", sessionKey)
lnConn.remoteNonceInt = 1 << 63
lnConn.myNonceInt = 0
lnConn.RemotePub = theirEphPub
lnConn.Authed = false
return myEph, nil
}
示例9: genRandomSig
// genRandomSig returns a random message, public key, and a signature of the
// message under the public key. This function is used to generate randomized
// test data.
func genRandomSig() (*wire.ShaHash, *btcec.Signature, *btcec.PublicKey, error) {
privKey, err := btcec.NewPrivateKey(btcec.S256())
if err != nil {
return nil, nil, nil, err
}
var msgHash wire.ShaHash
if _, err := rand.Read(msgHash[:]); err != nil {
return nil, nil, nil, err
}
sig, err := privKey.Sign(msgHash[:])
if err != nil {
return nil, nil, nil, err
}
return &msgHash, sig, privKey.PubKey(), nil
}
示例10: testSignAndVerify
func testSignAndVerify(t *testing.T, c *btcec.KoblitzCurve, tag string) {
priv, _ := btcec.NewPrivateKey(c)
pub := priv.PubKey()
hashed := []byte("testing")
sig, err := priv.Sign(hashed)
if err != nil {
t.Errorf("%s: error signing: %s", tag, err)
return
}
if !sig.Verify(hashed, pub) {
t.Errorf("%s: Verify failed", tag)
}
hashed[0] ^= 0xff
if sig.Verify(hashed, pub) {
t.Errorf("%s: Verify always works!", tag)
}
}
示例11: TestCipheringBasic
// Test 1: Encryption and decryption
func TestCipheringBasic(t *testing.T) {
privkey, err := btcec.NewPrivateKey(btcec.S256())
if err != nil {
t.Fatal("failed to generate private key")
}
in := []byte("Hey there dude. How are you doing? This is a test.")
out, err := btcec.Encrypt(privkey.PubKey(), in)
if err != nil {
t.Fatal("failed to encrypt:", err)
}
dec, err := btcec.Decrypt(privkey, out)
if err != nil {
t.Fatal("failed to decrypt:", err)
}
if !bytes.Equal(in, dec) {
t.Error("decrypted data doesn't match original")
}
}
示例12: TestSignTxOutput
func TestSignTxOutput(t *testing.T) {
t.Parallel()
// make key
// make script based on key.
// sign with magic pixie dust.
hashTypes := []SigHashType{
SigHashOld, // no longer used but should act like all
SigHashAll,
SigHashNone,
SigHashSingle,
SigHashAll | SigHashAnyOneCanPay,
SigHashNone | SigHashAnyOneCanPay,
SigHashSingle | SigHashAnyOneCanPay,
}
tx := &wire.MsgTx{
Version: 1,
TxIn: []*wire.TxIn{
{
PreviousOutPoint: wire.OutPoint{
Hash: chainhash.Hash{},
Index: 0,
},
Sequence: 4294967295,
},
{
PreviousOutPoint: wire.OutPoint{
Hash: chainhash.Hash{},
Index: 1,
},
Sequence: 4294967295,
},
{
PreviousOutPoint: wire.OutPoint{
Hash: chainhash.Hash{},
Index: 2,
},
Sequence: 4294967295,
},
},
TxOut: []*wire.TxOut{
{
Value: 1,
},
{
Value: 2,
},
{
Value: 3,
},
},
LockTime: 0,
}
// Pay to Pubkey Hash (uncompressed)
for _, hashType := range hashTypes {
for i := range tx.TxIn {
msg := fmt.Sprintf("%d:%d", hashType, i)
key, err := btcec.NewPrivateKey(btcec.S256())
if err != nil {
t.Errorf("failed to make privKey for %s: %v",
msg, err)
break
}
pk := (*btcec.PublicKey)(&key.PublicKey).
SerializeUncompressed()
address, err := btcutil.NewAddressPubKeyHash(
btcutil.Hash160(pk), &chaincfg.TestNet3Params)
if err != nil {
t.Errorf("failed to make address for %s: %v",
msg, err)
break
}
pkScript, err := PayToAddrScript(address)
if err != nil {
t.Errorf("failed to make pkscript "+
"for %s: %v", msg, err)
}
if err := signAndCheck(msg, tx, i, pkScript, hashType,
mkGetKey(map[string]addressToKey{
address.EncodeAddress(): {key, false},
}), mkGetScript(nil), nil); err != nil {
t.Error(err)
break
}
}
}
// Pay to Pubkey Hash (uncompressed) (merging with correct)
for _, hashType := range hashTypes {
for i := range tx.TxIn {
msg := fmt.Sprintf("%d:%d", hashType, i)
key, err := btcec.NewPrivateKey(btcec.S256())
if err != nil {
t.Errorf("failed to make privKey for %s: %v",
msg, err)
break
//.........这里部分代码省略.........
示例13: Dial
// Dial...
func (c *Conn) Dial(address string, remoteId []byte) error {
var err error
if c.conn != nil {
return fmt.Errorf("connection already established")
}
// Before dialing out to the remote host, verify that `remoteId` is either
// a pubkey or a pubkey hash.
if len(remoteId) != 33 && len(remoteId) != 20 {
return fmt.Errorf("must supply either remote pubkey or " +
"pubkey hash")
}
// First, open the TCP connection itself.
c.conn, err = net.Dial("tcp", address)
if err != nil {
return err
}
// Calc remote LNId; need this for creating pbx connections just because
// LNid is in the struct does not mean it's authed!
if len(remoteId) == 20 {
copy(c.remoteLNId[:], remoteId[:16])
} else {
theirAdr := btcutil.Hash160(remoteId)
copy(c.remoteLNId[:], theirAdr[:16])
}
// Make up an ephemeral keypair for this session.
ourEphemeralPriv, err := btcec.NewPrivateKey(btcec.S256())
if err != nil {
return err
}
ourEphemeralPub := ourEphemeralPriv.PubKey()
// Sned 1. Send my ephemeral pubkey. Can add version bits.
if _, err = writeClear(c.conn, ourEphemeralPub.SerializeCompressed()); err != nil {
return err
}
// Read, then deserialize their ephemeral public key.
theirEphPubBytes, err := readClear(c.conn)
if err != nil {
return err
}
theirEphPub, err := btcec.ParsePubKey(theirEphPubBytes, btcec.S256())
if err != nil {
return err
}
// Do non-interactive diffie with ephemeral pubkeys. Sha256 for good
// luck.
sessionKey := fastsha256.Sum256(
btcec.GenerateSharedSecret(ourEphemeralPriv, theirEphPub),
)
// Now that we've derive the session key, we can initialize the
// chacha20poly1305 AEAD instance which will be used for the remainder of
// the session.
c.chachaStream, err = chacha20poly1305.New(sessionKey[:])
if err != nil {
return err
}
// display private key for debug only
fmt.Printf("made session key %x\n", sessionKey)
c.myNonceInt = 1 << 63
c.remoteNonceInt = 0
c.remotePub = theirEphPub
c.authed = false
// Session is now open and confidential but not yet authenticated...
// So auth!
if len(remoteId) == 20 {
// Only know pubkey hash (20 bytes).
err = c.authPKH(remoteId, ourEphemeralPub.SerializeCompressed())
} else {
// Must be 33 byte pubkey.
err = c.authPubKey(remoteId, ourEphemeralPub.SerializeCompressed())
}
if err != nil {
return err
}
return nil
}
示例14: TestSphinxCorrectness
func TestSphinxCorrectness(t *testing.T) {
nodes := make([]*SphinxNode, numMaxHops)
// Create numMaxHops random sphinx nodes.
for i := 0; i < len(nodes); i++ {
privKey, err := btcec.NewPrivateKey(btcec.S256())
if err != nil {
t.Fatalf("Unable to generate random key for sphinx node: %v", err)
}
nodes[i] = NewSphinxNode(privKey, &chaincfg.MainNetParams)
}
// Gather all the pub keys in the path.
route := make([]*btcec.PublicKey, len(nodes))
for i := 0; i < len(nodes); i++ {
route[i] = nodes[i].lnKey.PubKey()
}
// Generate a forwarding message to route to the final node via the
// generated intermdiates nodes above.
// Destination should be Hash160, adding padding so parsing still works.
dest := append([]byte("roasbeef"), bytes.Repeat([]byte{0}, securityParameter-8)...)
fwdMsg, err := NewForwardingMessage(route, dest, []byte("testing"))
if err != nil {
t.Fatalf("Unable to create forwarding message: %#v", err)
}
// Now simulate the message propagating through the mix net eventually
// reaching the final destination.
for i := 0; i < len(nodes); i++ {
hop := nodes[i]
fmt.Printf("Processing at hop: %v \n", i)
processAction, err := hop.ProcessForwardingMessage(fwdMsg)
if err != nil {
t.Fatalf("Node %v was unabled to process the forwarding message: %v", i, err)
}
// If this is the last hop on the path, the node should
// recognize that it's the exit node.
if i == len(nodes)-1 {
if processAction.action != ExitNode {
t.Fatalf("Processing error, node %v is the last hop in"+
"the path, yet it doesn't recognize so", i)
}
// The original destination address and message should
// now be fully decrypted.
if !bytes.Equal(dest, processAction.destAddr) {
t.Fatalf("Destination address parsed incorrectly at final destination!"+
" Should be %v, is instead %v",
hex.EncodeToString(dest),
hex.EncodeToString(processAction.destAddr))
}
if !bytes.HasPrefix(processAction.destMsg, []byte("testing")) {
t.Fatalf("Final message parsed incorrectly at final destination!"+
"Should be %v, is instead %v",
[]byte("testing"), processAction.destMsg)
}
} else {
// If this isn't the last node in the path, then the returned
// action should indicate that there are more hops to go.
if processAction.action != MoreHops {
t.Fatalf("Processing error, node %v is not the final"+
" hop, yet thinks it is.", i)
}
// The next hop should have been parsed as node[i+1].
parsedNextHop := processAction.nextHop[:]
if !bytes.Equal(parsedNextHop, nodes[i+1].nodeID[:]) {
t.Fatalf("Processing error, next hop parsed incorrectly."+
" next hop shoud be %v, was instead parsed as %v",
hex.EncodeToString(nodes[i+1].nodeID[:]),
hex.EncodeToString(parsedNextHop))
}
fwdMsg = processAction.fwdMsg
}
}
}
示例15: TestCheckPkScriptStandard
// TestCheckPkScriptStandard tests the checkPkScriptStandard API.
func TestCheckPkScriptStandard(t *testing.T) {
var pubKeys [][]byte
for i := 0; i < 4; i++ {
pk, err := btcec.NewPrivateKey(btcec.S256())
if err != nil {
t.Fatalf("TestCheckPkScriptStandard NewPrivateKey failed: %v",
err)
return
}
pubKeys = append(pubKeys, pk.PubKey().SerializeCompressed())
}
tests := []struct {
name string // test description.
script *txscript.ScriptBuilder
isStandard bool
}{
{
"key1 and key2",
txscript.NewScriptBuilder().AddOp(txscript.OP_2).
AddData(pubKeys[0]).AddData(pubKeys[1]).
AddOp(txscript.OP_2).AddOp(txscript.OP_CHECKMULTISIG),
true,
},
{
"key1 or key2",
txscript.NewScriptBuilder().AddOp(txscript.OP_1).
AddData(pubKeys[0]).AddData(pubKeys[1]).
AddOp(txscript.OP_2).AddOp(txscript.OP_CHECKMULTISIG),
true,
},
{
"escrow",
txscript.NewScriptBuilder().AddOp(txscript.OP_2).
AddData(pubKeys[0]).AddData(pubKeys[1]).
AddData(pubKeys[2]).
AddOp(txscript.OP_3).AddOp(txscript.OP_CHECKMULTISIG),
true,
},
{
"one of four",
txscript.NewScriptBuilder().AddOp(txscript.OP_1).
AddData(pubKeys[0]).AddData(pubKeys[1]).
AddData(pubKeys[2]).AddData(pubKeys[3]).
AddOp(txscript.OP_4).AddOp(txscript.OP_CHECKMULTISIG),
false,
},
{
"malformed1",
txscript.NewScriptBuilder().AddOp(txscript.OP_3).
AddData(pubKeys[0]).AddData(pubKeys[1]).
AddOp(txscript.OP_2).AddOp(txscript.OP_CHECKMULTISIG),
false,
},
{
"malformed2",
txscript.NewScriptBuilder().AddOp(txscript.OP_2).
AddData(pubKeys[0]).AddData(pubKeys[1]).
AddOp(txscript.OP_3).AddOp(txscript.OP_CHECKMULTISIG),
false,
},
{
"malformed3",
txscript.NewScriptBuilder().AddOp(txscript.OP_0).
AddData(pubKeys[0]).AddData(pubKeys[1]).
AddOp(txscript.OP_2).AddOp(txscript.OP_CHECKMULTISIG),
false,
},
{
"malformed4",
txscript.NewScriptBuilder().AddOp(txscript.OP_1).
AddData(pubKeys[0]).AddData(pubKeys[1]).
AddOp(txscript.OP_0).AddOp(txscript.OP_CHECKMULTISIG),
false,
},
{
"malformed5",
txscript.NewScriptBuilder().AddOp(txscript.OP_1).
AddData(pubKeys[0]).AddData(pubKeys[1]).
AddOp(txscript.OP_CHECKMULTISIG),
false,
},
{
"malformed6",
txscript.NewScriptBuilder().AddOp(txscript.OP_1).
AddData(pubKeys[0]).AddData(pubKeys[1]),
false,
},
}
for _, test := range tests {
script, err := test.script.Script()
if err != nil {
t.Fatalf("TestCheckPkScriptStandard test '%s' "+
"failed: %v", test.name, err)
continue
}
scriptClass := txscript.GetScriptClass(script)
got := checkPkScriptStandard(script, scriptClass)
//.........这里部分代码省略.........