Skip to content

Commit 6817e1f

Browse files
committed
sighash: Improve documentation
Improve the rustdoc documentation in the `sighash` module by doing: - Improve grammar - Use full sentences (full stops and capitalisation) - Use 100 line column width - Use back ticks and links as appropriate - Improve correctness of `SigHashCache::new` function
1 parent bb495a2 commit 6817e1f

File tree

1 file changed

+69
-67
lines changed

1 file changed

+69
-67
lines changed

src/util/sighash.rs

Lines changed: 69 additions & 67 deletions
Original file line numberDiff line numberDiff line change
@@ -39,63 +39,63 @@ use super::taproot::LeafVersion;
3939
/// Efficiently calculates signature hash message for legacy, segwit and taproot inputs.
4040
#[derive(Debug)]
4141
pub struct SighashCache<T: Deref<Target=Transaction>> {
42-
/// Access to transaction required for various introspection, moreover type
43-
/// `T: Deref<Target=Transaction>` allows to accept borrow and mutable borrow, the
44-
/// latter in particular is necessary for [`SighashCache::witness_mut`]
42+
/// Access to transaction required for transaction introspection. Moreover, type
43+
/// `T: Deref<Target=Transaction>` allows us to use borrowed and mutable borrowed types,
44+
/// the latter in particular is necessary for [`SighashCache::witness_mut`].
4545
tx: T,
4646

47-
/// Common cache for taproot and segwit inputs. It's an option because it's not needed for legacy inputs
47+
/// Common cache for taproot and segwit inputs, `None` for legacy inputs.
4848
common_cache: Option<CommonCache>,
4949

50-
/// Cache for segwit v0 inputs, it's the result of another round of sha256 on `common_cache`
50+
/// Cache for segwit v0 inputs.
5151
segwit_cache: Option<SegwitCache>,
5252

53-
/// Cache for taproot v1 inputs
53+
/// Cache for taproot v1 inputs.
5454
taproot_cache: Option<TaprootCache>,
5555
}
5656

57-
/// Values cached common between segwit and taproot inputs
57+
/// Common values cached between segwit and taproot inputs.
5858
#[derive(Debug)]
5959
struct CommonCache {
6060
prevouts: sha256::Hash,
6161
sequences: sha256::Hash,
6262

63-
/// in theory, `outputs` could be `Option` since `NONE` and `SINGLE` doesn't need it, but since
64-
/// `ALL` is the mostly used variant by large, we don't bother
63+
/// In theory `outputs` could be an `Option` since `SIGHASH_NONE` and `SIGHASH_SINGLE` do not
64+
/// need it, but since `SIGHASH_ALL` is by far the most used variant we don't bother.
6565
outputs: sha256::Hash,
6666
}
6767

68-
/// Values cached for segwit inputs, it's equal to [`CommonCache`] plus another round of `sha256`
68+
/// Values cached for segwit inputs, equivalent to [`CommonCache`] plus another round of `sha256`.
6969
#[derive(Debug)]
7070
struct SegwitCache {
7171
prevouts: sha256d::Hash,
7272
sequences: sha256d::Hash,
7373
outputs: sha256d::Hash,
7474
}
7575

76-
/// Values cached for taproot inputs
76+
/// Values cached for taproot inputs.
7777
#[derive(Debug)]
7878
struct TaprootCache {
7979
amounts: sha256::Hash,
8080
script_pubkeys: sha256::Hash,
8181
}
8282

83-
/// Contains outputs of previous transactions.
84-
/// In the case [`SchnorrSighashType`] variant is `ANYONECANPAY`, [`Prevouts::One`] may be provided
83+
/// Contains outputs of previous transactions. In the case [`SchnorrSighashType`] variant is
84+
/// `SIGHASH_ANYONECANPAY`, [`Prevouts::One`] may be used.
8585
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
8686
pub enum Prevouts<'u, T> where T: 'u + Borrow<TxOut> {
87-
/// `One` variant allows to provide the single Prevout needed. It's useful for example
88-
/// when modifier `ANYONECANPAY` is provided, only prevout of the current input is needed.
87+
/// `One` variant allows provision of the single prevout needed. It's useful, for example, when
88+
/// modifier `SIGHASH_ANYONECANPAY` is provided, only prevout of the current input is needed.
8989
/// The first `usize` argument is the input index this [`TxOut`] is referring to.
9090
One(usize, T),
91-
/// When `ANYONECANPAY` is not provided, or the caller is handy giving all prevouts so the same
92-
/// variable can be used for multiple inputs.
91+
/// When `SIGHASH_ANYONECANPAY` is not provided, or when the caller is giving all prevouts so
92+
/// the same variable can be used for multiple inputs.
9393
All(&'u [T]),
9494
}
9595

9696
const KEY_VERSION_0: u8 = 0u8;
9797

98-
/// Information related to the script path spending
98+
/// Information related to the script path spending.
9999
///
100100
/// This can be hashed into a [`TapLeafHash`].
101101
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
@@ -104,29 +104,29 @@ pub struct ScriptPath<'s> {
104104
leaf_version: LeafVersion,
105105
}
106106

107-
/// Hashtype of an input's signature, encoded in the last byte of the signature
108-
/// Fixed values so they can be casted as integer types for encoding
107+
/// Hashtype of an input's signature, encoded in the last byte of the signature. Fixed values so
108+
/// they can be cast as integer types for encoding.
109109
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
110110
pub enum SchnorrSighashType {
111-
/// 0x0: Used when not explicitly specified, defaulting to [`SchnorrSighashType::All`]
111+
/// 0x0: Used when not explicitly specified, defaults to [`SchnorrSighashType::All`]
112112
Default = 0x00,
113-
/// 0x1: Sign all outputs
113+
/// 0x1: Sign all outputs.
114114
All = 0x01,
115-
/// 0x2: Sign no outputs --- anyone can choose the destination
115+
/// 0x2: Sign no outputs --- anyone can choose the destination.
116116
None = 0x02,
117117
/// 0x3: Sign the output whose index matches this input's index. If none exists,
118118
/// sign the hash `0000000000000000000000000000000000000000000000000000000000000001`.
119119
/// (This rule is probably an unintentional C++ism, but it's consensus so we have
120120
/// to follow it.)
121121
Single = 0x03,
122-
/// 0x81: Sign all outputs but only this input
122+
/// 0x81: Sign all outputs but only this input.
123123
AllPlusAnyoneCanPay = 0x81,
124-
/// 0x82: Sign no outputs and only this input
124+
/// 0x82: Sign no outputs and only this input.
125125
NonePlusAnyoneCanPay = 0x82,
126-
/// 0x83: Sign one output and only this input (see `Single` for what "one output" means)
126+
/// 0x83: Sign one output and only this input (see `Single` for what "one output" means).
127127
SinglePlusAnyoneCanPay = 0x83,
128128

129-
/// Reserved for future use, `#[non_exhaustive]` is not available with current MSRV
129+
/// Reserved for future use, `#[non_exhaustive]` is not available with MSRV 1.29.0
130130
Reserved = 0xFF,
131131
}
132132
serde_string_impl!(SchnorrSighashType, "a SchnorrSighashType data");
@@ -165,45 +165,46 @@ impl str::FromStr for SchnorrSighashType {
165165
}
166166
}
167167

168-
/// Possible errors in computing the signature message
168+
/// Possible errors in computing the signature message.
169169
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
170170
pub enum Error {
171171
/// Could happen only by using `*_encode_signing_*` methods with custom writers, engines writers
172-
/// like the ones used in methods `*_signature_hash` don't error
172+
/// like the ones used in methods `*_signature_hash` do not error.
173173
Io(io::ErrorKind),
174174

175-
/// Requested index is greater or equal than the number of inputs in the transaction
175+
/// Requested index is greater or equal than the number of inputs in the transaction.
176176
IndexOutOfInputsBounds {
177-
/// Requested index
177+
/// Requested index.
178178
index: usize,
179-
/// Number of transaction inputs
179+
/// Number of transaction inputs.
180180
inputs_size: usize,
181181
},
182182

183-
/// Using SIGHASH_SINGLE without a "corresponding output" (an output with the same index as the
184-
/// input being verified) is a validation failure
183+
/// Using `SIGHASH_SINGLE` without a "corresponding output" (an output with the same index as
184+
/// the input being verified) is a validation failure.
185185
SingleWithoutCorrespondingOutput {
186-
/// Requested index
186+
/// Requested index.
187187
index: usize,
188-
/// Number of transaction outputs
188+
/// Number of transaction outputs.
189189
outputs_size: usize,
190190
},
191191

192-
/// There are mismatches in the number of prevouts provided compared with the number of
193-
/// inputs in the transaction
192+
/// There are mismatches in the number of prevouts provided compared to the number of inputs in
193+
/// the transaction.
194194
PrevoutsSize,
195195

196196
/// Requested a prevout index which is greater than the number of prevouts provided or a
197-
/// [`Prevouts::One`] with different index
197+
/// [`Prevouts::One`] with different index.
198198
PrevoutIndex,
199199

200-
/// A single prevout has been provided but all prevouts are needed without `ANYONECANPAY`
200+
/// A single prevout has been provided but all prevouts are needed unless using
201+
/// `SIGHASH_ANYONECANPAY`.
201202
PrevoutKind,
202203

203-
/// Annex must be at least one byte long and the first bytes must be `0x50`
204+
/// Annex must be at least one byte long and the first bytes must be `0x50`.
204205
WrongAnnex,
205206

206-
/// Invalid Sighash type
207+
/// Invalid Sighash type.
207208
InvalidSighashType(u32),
208209
}
209210

@@ -260,18 +261,18 @@ impl<'u, T> Prevouts<'u, T> where T: Borrow<TxOut> {
260261
}
261262

262263
impl<'s> ScriptPath<'s> {
263-
/// Create a new ScriptPath structure
264+
/// Creates a new `ScriptPath` structure.
264265
pub fn new(script: &'s Script, leaf_version: LeafVersion) -> Self {
265266
ScriptPath {
266267
script,
267268
leaf_version,
268269
}
269270
}
270-
/// Create a new ScriptPath structure using default leaf version value
271+
/// Creates a new `ScriptPath` structure using default leaf version value.
271272
pub fn with_defaults(script: &'s Script) -> Self {
272273
Self::new(script, LeafVersion::TapScript)
273274
}
274-
/// Compute the leaf hash
275+
/// Computes the leaf hash for this `ScriptPath`.
275276
pub fn leaf_hash(&self) -> TapLeafHash {
276277
let mut enc = TapLeafHash::engine();
277278

@@ -302,7 +303,7 @@ impl From<EcdsaSighashType> for SchnorrSighashType {
302303
}
303304

304305
impl SchnorrSighashType {
305-
/// Break the sighash flag into the "real" sighash flag and the ANYONECANPAY boolean
306+
/// Breaks the sighash flag into the "real" sighash flag and the `SIGHASH_ANYONECANPAY` boolean.
306307
pub(crate) fn split_anyonecanpay_flag(self) -> (SchnorrSighashType, bool) {
307308
match self {
308309
SchnorrSighashType::Default => (SchnorrSighashType::Default, false),
@@ -316,7 +317,7 @@ impl SchnorrSighashType {
316317
}
317318
}
318319

319-
/// Create a [`SchnorrSighashType`] from raw `u8`
320+
/// Creates a [`SchnorrSighashType`] from raw `u8`.
320321
pub fn from_u8(hash_ty: u8) -> Result<Self, Error> {
321322
match hash_ty {
322323
0x00 => Ok(SchnorrSighashType::Default),
@@ -332,11 +333,12 @@ impl SchnorrSighashType {
332333
}
333334
}
334335

335-
impl<R: Deref<Target=Transaction>> SighashCache<R> {
336-
/// Compute the sighash components from an unsigned transaction and auxiliary
337-
/// in a lazy manner when required.
338-
/// For the generated sighashes to be valid, no fields in the transaction may change except for
339-
/// script_sig and witnesses.
336+
impl<R: Deref<Target = Transaction>> SighashCache<R> {
337+
/// Constructs a new `SighashCache` from an unsigned transaction.
338+
///
339+
/// The sighash components are computed in a lazy manner when required. For the generated
340+
/// sighashes to be valid, no fields in the transaction may change except for script_sig and
341+
/// witness.
340342
pub fn new(tx: R) -> Self {
341343
SighashCache {
342344
tx,
@@ -346,8 +348,8 @@ impl<R: Deref<Target=Transaction>> SighashCache<R> {
346348
}
347349
}
348350

349-
/// Encode the BIP341 signing data for any flag type into a given object implementing a
350-
/// io::Write trait.
351+
/// Encodes the BIP341 signing data for any flag type into a given object implementing a
352+
/// `io::Write` trait.
351353
pub fn taproot_encode_signing_data_to<Write: io::Write, T: Borrow<TxOut>>(
352354
&mut self,
353355
mut writer: Write,
@@ -477,7 +479,7 @@ impl<R: Deref<Target=Transaction>> SighashCache<R> {
477479
Ok(())
478480
}
479481

480-
/// Compute the BIP341 sighash for any flag type.
482+
/// Computes the BIP341 sighash for any flag type.
481483
pub fn taproot_signature_hash<T: Borrow<TxOut>>(
482484
&mut self,
483485
input_index: usize,
@@ -498,7 +500,7 @@ impl<R: Deref<Target=Transaction>> SighashCache<R> {
498500
Ok(TapSighashHash::from_engine(enc))
499501
}
500502

501-
/// Compute the BIP341 sighash for a key spend
503+
/// Computes the BIP341 sighash for a key spend.
502504
pub fn taproot_key_spend_signature_hash<T: Borrow<TxOut>>(
503505
&mut self,
504506
input_index: usize,
@@ -517,7 +519,7 @@ impl<R: Deref<Target=Transaction>> SighashCache<R> {
517519
Ok(TapSighashHash::from_engine(enc))
518520
}
519521

520-
/// Compute the BIP341 sighash for a script spend
522+
/// Computes the BIP341 sighash for a script spend.
521523
///
522524
/// Assumes the default `OP_CODESEPARATOR` position of `0xFFFFFFFF`. Custom values can be
523525
/// provided through the more fine-grained API of [`SighashCache::taproot_encode_signing_data_to`].
@@ -540,7 +542,7 @@ impl<R: Deref<Target=Transaction>> SighashCache<R> {
540542
Ok(TapSighashHash::from_engine(enc))
541543
}
542544

543-
/// Encode the BIP143 signing data for any flag type into a given object implementing a
545+
/// Encodes the BIP143 signing data for any flag type into a given object implementing a
544546
/// [`std::io::Write`] trait.
545547
pub fn segwit_encode_signing_data_to<Write: io::Write>(
546548
&mut self,
@@ -605,7 +607,7 @@ impl<R: Deref<Target=Transaction>> SighashCache<R> {
605607
Ok(())
606608
}
607609

608-
/// Compute the BIP143 sighash for any flag type.
610+
/// Computes the BIP143 sighash for any flag type.
609611
pub fn segwit_signature_hash(
610612
&mut self,
611613
input_index: usize,
@@ -624,8 +626,8 @@ impl<R: Deref<Target=Transaction>> SighashCache<R> {
624626
Ok(Sighash::from_engine(enc))
625627
}
626628

627-
/// Encode the legacy signing data for any flag type into a given object implementing a
628-
/// [`std::io::Write`] trait. Internally calls [`Transaction::encode_signing_data_to`]
629+
/// Encodes the legacy signing data for any flag type into a given object implementing a
630+
/// [`std::io::Write`] trait. Internally calls [`Transaction::encode_signing_data_to`].
629631
pub fn legacy_encode_signing_data_to<Write: io::Write, U: Into<u32>>(
630632
&self,
631633
mut writer: Write,
@@ -645,7 +647,7 @@ impl<R: Deref<Target=Transaction>> SighashCache<R> {
645647
Ok(())
646648
}
647649

648-
/// Computes the legacy sighash for any sighash type.
650+
/// Computes the legacy sighash for any `sighash_type`.
649651
pub fn legacy_signature_hash(
650652
&self,
651653
input_index: usize,
@@ -730,8 +732,8 @@ impl<R: Deref<Target=Transaction>> SighashCache<R> {
730732
}
731733

732734
impl<R: DerefMut<Target=Transaction>> SighashCache<R> {
733-
/// When the SighashCache is initialized with a mutable reference to a transaction instead of a
734-
/// regular reference, this method is available to allow modification to the witnesses.
735+
/// When the `SighashCache` is initialized with a mutable reference to a transaction instead of
736+
/// a regular reference, this method is available to allow modification to the witnesses.
735737
///
736738
/// This allows in-line signing such as
737739
/// ```
@@ -761,12 +763,12 @@ impl From<io::Error> for Error {
761763
}
762764
}
763765

764-
/// The `Annex` struct is a slice wrapper enforcing first byte to be `0x50`.
766+
/// The `Annex` struct is a slice wrapper enforcing first byte is `0x50`.
765767
#[derive(Clone, PartialEq, Eq, Hash, Debug)]
766768
pub struct Annex<'a>(&'a [u8]);
767769

768770
impl<'a> Annex<'a> {
769-
/// Creates a new `Annex` struct checking the first byte is `0x50`
771+
/// Creates a new `Annex` struct checking the first byte is `0x50`.
770772
pub fn new(annex_bytes: &'a [u8]) -> Result<Self, Error> {
771773
if annex_bytes.first() == Some(&TAPROOT_ANNEX_PREFIX) {
772774
Ok(Annex(annex_bytes))
@@ -775,7 +777,7 @@ impl<'a> Annex<'a> {
775777
}
776778
}
777779

778-
/// Returns the Annex bytes data (including first byte `0x50`)
780+
/// Returns the Annex bytes data (including first byte `0x50`).
779781
pub fn as_bytes(&self) -> &[u8] {
780782
&*self.0
781783
}

0 commit comments

Comments
 (0)