api.rs (7239B)
1 /* 2 This file is part of TALER 3 Copyright (C) 2024, 2025, 2026 Taler Systems SA 4 5 TALER is free software; you can redistribute it and/or modify it under the 6 terms of the GNU Affero General Public License as published by the Free Software 7 Foundation; either version 3, or (at your option) any later version. 8 9 TALER is distributed in the hope that it will be useful, but WITHOUT ANY 10 WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR 11 A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. 12 13 You should have received a copy of the GNU Affero General Public License along with 14 TALER; see the file COPYING. If not, see <http://www.gnu.org/licenses/> 15 */ 16 17 use std::{borrow::Cow, fmt::Display, num::ParseIntError, ops::Deref, str::FromStr}; 18 19 use aws_lc_rs::{ 20 error::KeyRejected, 21 signature::{self, Ed25519KeyPair, KeyPair as _, ParsedPublicKey}, 22 }; 23 use serde::{Deserialize, Deserializer, Serialize}; 24 use serde_json::value::RawValue; 25 26 use crate::{encoding::base32::Base32Error, types::base32::Base32}; 27 28 pub mod observability; 29 pub mod params; 30 pub mod prepared; 31 pub mod revenue; 32 pub mod wire; 33 34 #[derive( 35 Debug, 36 Clone, 37 Copy, 38 PartialEq, 39 Eq, 40 PartialOrd, 41 Ord, 42 Hash, 43 serde_with::DeserializeFromStr, 44 serde_with::SerializeDisplay, 45 )] 46 pub struct LibtoolVersion { 47 pub current: u32, 48 pub revision: u32, 49 pub age: u32, 50 } 51 52 impl LibtoolVersion { 53 pub const fn new(current: u32, revision: u32, age: u32) -> Self { 54 assert!(age <= current); 55 Self { 56 current, 57 revision, 58 age, 59 } 60 } 61 } 62 63 #[derive(Debug, thiserror::Error)] 64 pub enum LibtoolVersionError { 65 #[error("age exceeds current")] 66 AgeExceedsCurrent, 67 #[error("invalid format")] 68 InvalidFormat, 69 #[error(transparent)] 70 ParseIntError(#[from] ParseIntError), 71 } 72 73 impl FromStr for LibtoolVersion { 74 type Err = LibtoolVersionError; 75 76 fn from_str(s: &str) -> Result<Self, Self::Err> { 77 let mut parts = s.split(':'); 78 79 let current = parts 80 .next() 81 .ok_or(LibtoolVersionError::InvalidFormat)? 82 .parse::<u32>()?; 83 84 let revision = match parts.next() { 85 Some(p) => p.parse::<u32>()?, 86 None => 0, 87 }; 88 89 let age = match parts.next() { 90 Some(p) => p.parse::<u32>()?, 91 None => 0, 92 }; 93 94 if parts.next().is_some() { 95 return Err(LibtoolVersionError::InvalidFormat); 96 } 97 98 if age > current { 99 return Err(LibtoolVersionError::AgeExceedsCurrent); 100 } 101 102 Ok(Self::new(current, revision, age)) 103 } 104 } 105 106 impl Display for LibtoolVersion { 107 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 108 write!(f, "{}:{}:{}", self.current, self.revision, self.age) 109 } 110 } 111 112 /// <https://docs.taler.net/core/api-common.html#tsref-type-ErrorDetail> 113 #[derive(Debug, Clone, Serialize, Deserialize)] 114 pub struct ErrorDetail { 115 pub code: u32, 116 pub hint: Option<Box<str>>, 117 pub detail: Option<Box<str>>, 118 pub parameter: Option<Box<str>>, 119 pub path: Option<Box<str>>, 120 pub offset: Option<Box<str>>, 121 pub index: Option<Box<str>>, 122 pub object: Option<Box<str>>, 123 pub currency: Option<Box<str>>, 124 pub type_expected: Option<Box<str>>, 125 pub type_actual: Option<Box<str>>, 126 pub extra: Option<Box<RawValue>>, 127 } 128 129 /// 64-byte hash code 130 pub type HashCode = Base32<64>; 131 /// 32-bytes hash code 132 pub type ShortHashCode = Base32<32>; 133 pub type WadId = Base32<24>; 134 pub type EddsaSignature = Base32<64>; 135 136 /// EdDSA and ECDHE public keys always point on Curve25519 137 /// and represented using the standard 256 bits Ed25519 compact format, 138 /// converted to Crockford Base32. 139 #[derive(Clone, Copy, PartialEq, Eq)] 140 pub struct EddsaPublicKey(Base32<32>); 141 142 impl Deref for EddsaPublicKey { 143 type Target = Base32<32>; 144 145 fn deref(&self) -> &Self::Target { 146 &self.0 147 } 148 } 149 150 impl Serialize for EddsaPublicKey { 151 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> 152 where 153 S: serde::Serializer, 154 { 155 self.0.serialize(serializer) 156 } 157 } 158 159 impl<'de> Deserialize<'de> for EddsaPublicKey { 160 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> 161 where 162 D: Deserializer<'de>, 163 { 164 let raw = Cow::<str>::deserialize(deserializer)?; 165 Self::from_str(&raw).map_err(serde::de::Error::custom) 166 } 167 } 168 169 impl Display for EddsaPublicKey { 170 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 171 self.0.fmt(f) 172 } 173 } 174 175 impl std::fmt::Debug for EddsaPublicKey { 176 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 177 Display::fmt(&self.0, f) 178 } 179 } 180 181 #[derive(Debug, thiserror::Error)] 182 pub enum EddsaPublicKeyError { 183 #[error(transparent)] 184 Base32(#[from] Base32Error<32>), 185 #[error(transparent)] 186 Invalid(#[from] KeyRejected), 187 } 188 189 impl FromStr for EddsaPublicKey { 190 type Err = EddsaPublicKeyError; 191 192 fn from_str(s: &str) -> Result<Self, Self::Err> { 193 let encoded = Base32::<32>::from_str(s)?; 194 Self::try_from(encoded) 195 } 196 } 197 198 impl TryFrom<&[u8]> for EddsaPublicKey { 199 type Error = EddsaPublicKeyError; 200 201 fn try_from(value: &[u8]) -> Result<Self, Self::Error> { 202 let encoded = Base32::try_from(value)?; 203 Self::try_from(encoded) 204 } 205 } 206 207 impl TryFrom<[u8; 32]> for EddsaPublicKey { 208 type Error = EddsaPublicKeyError; 209 210 fn try_from(value: [u8; 32]) -> Result<Self, Self::Error> { 211 let encoded = Base32::from(value); 212 Self::try_from(encoded) 213 } 214 } 215 216 impl TryFrom<Base32<32>> for EddsaPublicKey { 217 type Error = EddsaPublicKeyError; 218 219 fn try_from(value: Base32<32>) -> Result<Self, Self::Error> { 220 ParsedPublicKey::new(&signature::ED25519, value.as_ref())?; 221 Ok(Self(value)) 222 } 223 } 224 225 impl EddsaPublicKey { 226 pub fn rand() -> EddsaPublicKey { 227 let signing_key = Ed25519KeyPair::generate().unwrap(); 228 let bytes: [u8; 32] = signing_key.public_key().as_ref().try_into().unwrap(); 229 Self(Base32::from(bytes)) 230 } 231 } 232 233 impl sqlx::Type<sqlx::Postgres> for EddsaPublicKey { 234 fn type_info() -> sqlx::postgres::PgTypeInfo { 235 <Base32<32>>::type_info() 236 } 237 } 238 239 impl<'q> sqlx::Encode<'q, sqlx::Postgres> for EddsaPublicKey { 240 fn encode_by_ref( 241 &self, 242 buf: &mut sqlx::postgres::PgArgumentBuffer, 243 ) -> Result<sqlx::encode::IsNull, sqlx::error::BoxDynError> { 244 self.0.encode_by_ref(buf) 245 } 246 } 247 248 impl<'r> sqlx::Decode<'r, sqlx::Postgres> for EddsaPublicKey { 249 fn decode(value: sqlx::postgres::PgValueRef<'r>) -> Result<Self, sqlx::error::BoxDynError> { 250 let raw = <Base32<32>>::decode(value)?; 251 Ok(Self::try_from(raw)?) 252 } 253 } 254 255 #[cfg(test)] 256 mod test { 257 use std::str::FromStr as _; 258 259 use super::{LibtoolVersion, LibtoolVersionError}; 260 261 #[test] 262 fn libtool_version_from_str() { 263 assert_eq!( 264 LibtoolVersion::from_str("5:2:1").unwrap(), 265 LibtoolVersion::new(5, 2, 1) 266 ); 267 assert!(matches!( 268 LibtoolVersion::from_str("1:0:2"), 269 Err(LibtoolVersionError::AgeExceedsCurrent) 270 )); 271 } 272 }