| 设置 | 值 |
|---|---|
| 地址 | <host>:9000,UDP,见端点 |
| ALPN | solana-tpu |
| 服务器名称 | soyas-landing(中继不检查它) |
| 客户端证书 | X.509,自签名即可,其公钥为您 API 密钥的 Ed25519 公钥;握手以 Ed25519 签名 |
| 服务器证书 | 自签名;其 DER 形式的 SHA-256 为 endpoints.json 中的 quic.tlsCertSha256。中继不要求您校验它。 |
您的 API 密钥来自控制台,从不通过 QUIC 发送:您的客户端用它生成证书,并用其私钥对握手签名。中继不检查任何证书颁发机构,只检查密钥。
use anyhow::Context as _;use quinn::{crypto::rustls::QuicClientConfig, ClientConfig, Connection, Endpoint, IdleTimeout, TransportConfig};use solana_sdk::signature::Keypair;use solana_tls_utils::{new_dummy_x509_certificate, SkipServerVerification};use std::{net::ToSocketAddrs as _, sync::Arc, time::Duration};
const ALPN: &[u8] = b"solana-tpu";const SERVER_NAME: &str = "soyas-landing";const KEEP_ALIVE: Duration = Duration::from_secs(25);const IDLE_TIMEOUT: Duration = Duration::from_secs(30);
// addr: "fra.landing.soyas.xyz:9000". api_key: the base58 keypair from the dashboard.async fn connect(addr: &str, api_key: &str) -> anyhow::Result<Connection> { let _ = rustls::crypto::ring::default_provider().install_default(); // rustls needs one per process let (cert, key) = new_dummy_x509_certificate(&Keypair::from_base58_string(api_key)); let mut crypto = rustls::ClientConfig::builder() .dangerous() .with_custom_certificate_verifier(SkipServerVerification::new()) // the relay's certificate is self-signed .with_client_auth_cert(vec![cert], key)?; crypto.alpn_protocols = vec![ALPN.to_vec()];
let mut transport = TransportConfig::default(); transport.keep_alive_interval(Some(KEEP_ALIVE)); transport.max_idle_timeout(Some(IdleTimeout::try_from(IDLE_TIMEOUT)?)); let mut config = ClientConfig::new(Arc::new(QuicClientConfig::try_from(crypto)?)); config.transport_config(Arc::new(transport));
let mut endpoint = Endpoint::client("0.0.0.0:0".parse()?)?; endpoint.set_default_client_config(config); let addr = addr.to_socket_addrs()?.next().context("address not resolved")?; Ok(endpoint.connect(addr, SERVER_NAME)?.await?)}
// One stream per transaction. tx: its wire bytes (bincode::serialize(&tx)?).async fn send(conn: &Connection, tx: &[u8]) -> anyhow::Result<()> { let mut stream = conn.open_uni().await?; stream.write_all(tx).await?; stream.finish()?; Ok(())}import ( "context" "crypto/ed25519" "crypto/rand" "crypto/tls" "crypto/x509" "errors" "math/big" "time"
"github.com/mr-tron/base58" "github.com/quic-go/quic-go" // v0.48)
const ( alpn = "solana-tpu" serverName = "soyas-landing" keepAlive = 25 * time.Second idleTimeout = 30 * time.Second)
// addr: "fra.landing.soyas.xyz:9000". apiKey: the base58 keypair from the dashboard.func connect(ctx context.Context, addr, apiKey string) (quic.Connection, error) { raw, err := base58.Decode(apiKey) if err != nil || len(raw) != ed25519.PrivateKeySize { return nil, errors.New("the API key is not a base58 64-byte keypair") } key := ed25519.NewKeyFromSeed(raw[:ed25519.SeedSize]) template := &x509.Certificate{ SerialNumber: big.NewInt(1), NotBefore: time.Now().Add(-time.Hour), NotAfter: time.Now().Add(365 * 24 * time.Hour), } cert, err := x509.CreateCertificate(rand.Reader, template, template, key.Public(), key) if err != nil { return nil, err } return quic.DialAddr(ctx, addr, &tls.Config{ Certificates: []tls.Certificate{{Certificate: [][]byte{cert}, PrivateKey: key}}, NextProtos: []string{alpn}, ServerName: serverName, InsecureSkipVerify: true, // the relay's certificate is self-signed MinVersion: tls.VersionTLS13, }, &quic.Config{KeepAlivePeriod: keepAlive, MaxIdleTimeout: idleTimeout})}
// One stream per transaction. tx: its wire bytes (solana-go: tx.MarshalBinary()).func send(ctx context.Context, conn quic.Connection, tx []byte) error { stream, err := conn.OpenUniStreamSync(ctx) if err != nil { return err } if _, err := stream.Write(tx); err != nil { return err } return stream.Close()}import asyncioimport sslfrom contextlib import asynccontextmanagerfrom datetime import datetime, timedelta, timezone
import base58from aioquic.asyncio.client import connect as quic_connectfrom aioquic.quic.configuration import QuicConfigurationfrom cryptography import x509from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKeyfrom cryptography.x509.oid import NameOID
ALPN = "solana-tpu"SERVER_NAME = "soyas-landing"KEEP_ALIVE = 25.0IDLE_TIMEOUT = 30.0
# host: "fra.landing.soyas.xyz", port: 9000. api_key: the base58 keypair from the dashboard.# async with connect(host, port, api_key) as protocol: send(protocol, tx)@asynccontextmanagerasync def connect(host: str, port: int, api_key: str): key = Ed25519PrivateKey.from_private_bytes(base58.b58decode(api_key)[:32]) name = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, "soyas-client")]) now = datetime.now(timezone.utc) config = QuicConfiguration( is_client=True, alpn_protocols=[ALPN], server_name=SERVER_NAME, verify_mode=ssl.CERT_NONE, # the relay's certificate is self-signed idle_timeout=IDLE_TIMEOUT, ) config.certificate = ( x509.CertificateBuilder() .subject_name(name) .issuer_name(name) .public_key(key.public_key()) .serial_number(x509.random_serial_number()) .not_valid_before(now - timedelta(hours=1)) .not_valid_after(now + timedelta(days=365)) .sign(key, None) ) config.private_key = key async with quic_connect(host, port, configuration=config) as protocol: pinging = asyncio.create_task(keep_alive(protocol)) try: yield protocol finally: pinging.cancel()
async def keep_alive(protocol): # aioquic has no keep-alive setting. while True: await asyncio.sleep(KEEP_ALIVE) await protocol.ping()
# One stream per transaction. tx: its wire bytes (solders: bytes(tx)).def send(protocol, tx: bytes) -> None: stream_id = protocol._quic.get_next_available_stream_id(is_unidirectional=True) protocol._quic.send_stream_data(stream_id, tx, end_stream=True) protocol.transmit()一个流承载一笔以 Solana 线格式编码的交易;中继将其读到末尾。不允许使用双向流。一个 QUIC 数据报也承载一笔交易。
对每个端点保持一个持久连接并复用它。结束您打开的每一个流:未结束的流已经占用了您速率限制中的一笔交易。
没有:没有确认,没有签名,没有错误。您的客户端写入并结束一个流,仅表示这些字节已交给 QUIC。如需每笔交易都有应答,请使用 HTTP。
| 情况 | 您的客户端看到的结果 |
|---|---|
| 证书的密钥不是 Ed25519,或握手签名错误 | TLS 握手失败。 |
| 没有客户端证书,或中继不认识该密钥 | 握手完成,随后连接以应用错误码 0 和原因 NotWhitelisted 关闭。 |
| 同一密钥打开的连接过多 | 最早的连接以应用错误码 0 和原因 TooManyConnections 关闭。 |
| 连接期间密钥被移除或停用 | 连接保持打开,其上的每笔交易都被丢弃;密钥恢复后,同一连接重新可用。 |
| 交易为空、无法解析、没有签名或签名者、超出下方某项限制、没有小费,或超出您的速率限制 | 被丢弃,不作任何通知。 |
| 限制 | 值 |
|---|---|
| 连接 | 对每个端点复用一个持久连接 |
| 流长度 | 8192 字节 |
| Legacy 与 v0 交易 | 1232 字节 |
| v1 交易 | 4096 字节 |
| 每秒交易数 | 您账户的速率限制,按端点计算,与 HTTP 共用;流在被接受时、读取之前即计数 |
| 空闲超时 | 30 s。中继不发送保活包:请以更短的间隔自行发送(上面的代码使用 25 s)。 |
