Struct rings_core::ecc::PublicKey

source ·
pub struct PublicKey(pub [u8; 33]);
Expand description

PublicKey for ECDSA and EdDSA.

Tuple Fields§

§0: [u8; 33]

Implementations§

trezor style b58

monero and bitcoin style b58

Examples found in repository?
src/ecc/types.rs (line 75)
73
74
75
76
    fn visit_str<E>(self, value: &str) -> std::result::Result<Self::Value, E>
    where E: serde::de::Error {
        PublicKey::try_from_b58m(value).map_err(|e| E::custom(e))
    }

monero style uncheck base56

from raw u8, the length can be 32, or 33

Examples found in repository?
src/ecc/types.rs (line 28)
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
    pub fn try_from_b58t(value: &str) -> Result<PublicKey> {
        let value: Vec<u8> =
            base58::FromBase58::from_base58(value).map_err(|_| Error::PublicKeyBadFormat)?;
        Self::from_u8(value.as_slice())
    }

    /// monero and bitcoin style b58
    pub fn try_from_b58m(value: &str) -> Result<PublicKey> {
        let value: &[u8] =
            &base58_monero::decode_check(value).map_err(|_| Error::PublicKeyBadFormat)?;
        Self::from_u8(value)
    }

    /// monero style uncheck base56
    pub fn try_from_b58m_uncheck(value: &str) -> Result<PublicKey> {
        let value: &[u8] = &base58_monero::decode(value).map_err(|_| Error::PublicKeyBadFormat)?;
        Self::from_u8(value)
    }

convert pubkey to base58_string

Examples found in repository?
src/ecc/signers.rs (line 32)
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
    pub fn verify(msg: &str, address: &Address, sig: impl AsRef<[u8]>) -> bool {
        if let Ok(p) = recover(msg, sig) {
            p.address() == *address
        } else {
            false
        }
    }
}

/// eip191.
/// ref <https://eips.ethereum.org/EIPS/eip-191>
pub mod eip191 {
    use super::*;

    /// sign function passing raw message parameter.
    pub fn sign_raw(sec: SecretKey, msg: &str) -> [u8; 65] {
        sign(sec, &hash(msg))
    }

    /// sign function with `hash` data.
    pub fn sign(sec: SecretKey, hash: &[u8; 32]) -> [u8; 65] {
        let mut sig = sec.sign_hash(hash);
        sig[64] += 27;
        sig
    }

    /// \x19Ethereum Signed Message\n use for PersionSign, which can encode by send `personalSign` rpc call.
    pub fn hash(msg: &str) -> [u8; 32] {
        let mut prefix_msg = format!("\x19Ethereum Signed Message:\n{}", msg.len()).into_bytes();
        prefix_msg.extend_from_slice(msg.as_bytes());
        keccak256(&prefix_msg)
    }

    /// recover pubkey according to signature.
    pub fn recover(msg: &str, sig: impl AsRef<[u8]>) -> Result<PublicKey> {
        let sig_byte: [u8; 65] = sig.as_ref().try_into()?;
        let hash = hash(msg);
        let mut sig712 = sig_byte;
        sig712[64] -= 27;
        crate::ecc::recover_hash(&hash, &sig712)
    }

    /// verify message signed by Ethereum address.
    pub fn verify(msg: &str, address: &Address, sig: impl AsRef<[u8]>) -> bool {
        if let Ok(p) = recover(msg, sig) {
            p.address() == *address
        } else {
            false
        }
    }
}

/// ed25519 sign algorithm using ed25519_dalek
pub mod ed25519 {
    use ed25519_dalek::Verifier;

    use super::*;

    /// ref <https://www.rfc-editor.org/rfc/rfc8709>
    pub fn verify(msg: &str, address: &Address, sig: impl AsRef<[u8]>, pubkey: PublicKey) -> bool {
        if pubkey.address() != *address {
            return false;
        }
        if sig.as_ref().len() != 64 {
            return false;
        }
        let sig_data: [u8; 64] = sig.as_ref().try_into().unwrap();
        if let (Ok(p), Ok(s)) = (
            TryInto::<ed25519_dalek::PublicKey>::try_into(pubkey),
            ed25519_dalek::Signature::from_bytes(&sig_data),
        ) {
            match p.verify(msg.as_bytes(), &s) {
                Ok(()) => true,
                Err(_) => false,
            }
        } else {
            false
        }
    }
More examples
Hide additional examples
src/session.rs (line 179)
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
    pub fn gen_unsign_info_with_pubkey(
        ttl: Option<Ttl>,
        signer: Option<Signer>,
        pubkey: PublicKey,
    ) -> Result<(AuthorizedInfo, SecretKey)> {
        let key = SecretKey::random();
        let signer = signer.unwrap_or(Signer::DEFAULT);
        let authorizer = Authorizer {
            did: pubkey.address().into(),
            pubkey: Some(pubkey),
        };
        let info = AuthorizedInfo {
            signer,
            authorizer,
            did: key.address().into(),
            ttl_ms: ttl.unwrap_or(Ttl::Some(DEFAULT_SESSION_TTL_MS)),
            ts_ms: utils::get_epoch_ms(),
        };
        Ok((info, key))
    }
src/transports/default/transport.rs (line 316)
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
    async fn on_ice_connection_state_change(&self) -> Self::OnIceConnectionStateChangeHdlrFn {
        let event_sender = self.event_sender.clone();
        let public_key = Arc::clone(&self.public_key);
        let id = self.id;
        box move |cs: RTCIceConnectionState| {
            let event_sender = event_sender.clone();
            let public_key = Arc::clone(&public_key);
            let id = id;
            Box::pin(async move {
                match cs {
                    RTCIceConnectionState::Connected => {
                        let local_did = public_key.read().await.unwrap().address().into();
                        if AcChannel::send(&event_sender, Event::RegisterTransport((local_did, id)))
                            .await
                            .is_err()
                        {
                            tracing::error!("Failed when send RegisterTransport");
                        }
                    }
                    RTCIceConnectionState::Failed
                    | RTCIceConnectionState::Disconnected
                    | RTCIceConnectionState::Closed => {
                        let local_did = public_key.read().await.unwrap().address().into();
                        if AcChannel::send(&event_sender, Event::ConnectClosed((local_did, id)))
                            .await
                            .is_err()
                        {
                            tracing::error!("Failed when send RegisterTransport");
                        }
                    }
                    _ => {
                        tracing::debug!("IceTransport state change {:?}", cs);
                    }
                }
            })
        }
    }

Trait Implementations§

Returns a copy of the value. Read more
Performs copy-assignment from source. Read more
Formats the value using the given formatter. Read more
Deserialize this value from the given Serde deserializer. Read more
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
This method tests for self and other values to be equal, and is used by ==.
This method tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Serialize this value into the given Serde serializer. Read more
The type returned in the event of a conversion error.
Performs the conversion.
The type returned in the event of a conversion error.
Performs the conversion.
The type returned in the event of a conversion error.
Performs the conversion.
The type returned in the event of a conversion error.
Performs the conversion.

Auto Trait Implementations§

Blanket Implementations§

Gets the TypeId of self. Read more
Immutably borrows from an owned value. Read more
Mutably borrows from an owned value. Read more
Compare self to key and return true if they are equal.

Returns the argument unchanged.

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Instruments this type with the current Span, returning an Instrumented wrapper. Read more

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

The alignment of pointer.
The type for initializers.
Initializes a with the given initializer. Read more
Dereferences the given pointer. Read more
Mutably dereferences the given pointer. Read more
Drops the object pointed to by the given pointer. Read more
Should always be Self
The resulting type after obtaining ownership.
Creates owned data from borrowed data, usually by cloning. Read more
Uses borrowed data to replace owned data, usually by cloning. Read more
The type returned in the event of a conversion error.
Performs the conversion.
The type returned in the event of a conversion error.
Performs the conversion.
Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more