Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: RPC endpoint /v2/traits/<contract-info>/<trait-info> #2498

Merged
merged 4 commits into from
Mar 11, 2021
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,9 @@ compatible with prior chainstate directories.
- Log transactions in local db table via setting env `STACKS_TRANSACTION_LOG=1`
- New prometheus metrics for mempool transaction processing times and
outstanding mempool transactions
- New RPC endpoint with path `v2/traits/contractAddr/contractName/traitContractName
/traitContractAddr/traitName` to determine whether a given trait is implemented
within the specified contract (either explicitly or implicitly).

## Changed

Expand Down
6 changes: 6 additions & 0 deletions docs/rpc-endpoints.md
Original file line number Diff line number Diff line change
Expand Up @@ -338,3 +338,9 @@ object of the following form:
"cause": "Unchecked(PublicFunctionNotReadOnly(..."
}
```

### GET /v2/traits/[Stacks Address]/[Contract Name]/[Trait Stacks Address]/[Trait Contract Name]/[Trait Name]

Determine whether a given trait is implemented within the specified contract (either explicitly or implicitly).

See OpenAPI [spec](./rpc/openapi.yaml) for details.
3 changes: 3 additions & 0 deletions docs/rpc/api/trait/get-is-trait-implemented.example.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"is_implemented": true
}
13 changes: 13 additions & 0 deletions docs/rpc/api/trait/get-is-trait-implemented.schema.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"description": "GET request to get trait implementation information",
"title": "IsTraitImplementedSuccessResponse",
"type": "object",
"additionalProperties": false,
"required": ["is_implemented"],
"properties": {
"is_implemented": {
"type": "boolean"
},
}
}
53 changes: 53 additions & 0 deletions docs/rpc/openapi.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -326,3 +326,56 @@ paths:
$ref: ./api/core-node/get-pox.schema.json
example:
$ref: ./api/core-node/get-pox.example.json

/v2/traits/{contract_address}/{contract_name}/{trait_contract_address}/{trait_ contract_name}/{trait_name}:
get:
summary: Get trait implementation details
description: Determine whether or not a specified trait is implemented (either explicitly or implicitly) within a given contract.
tags:
- Info
pavitthrap marked this conversation as resolved.
Show resolved Hide resolved
operationId: get_is_trait_implemented
responses:
200:
description: Success
content:
application/json:
schema:
$ref: ./api/trait/get-is-trait-implemented.schema.json
example:
$ref: ./api/trait/get-is-trait-implemented.example.json
parameters:
- name: contract_address
in: path
required: true
description: Stacks address
schema:
type: string
- name: contract_name
in: path
required: true
description: Contract name
schema:
type: string
- name: trait_contract_address
in: path
required: true
description: Trait Stacks address
schema:
type: string
- name: trait_contract_name
in: path
required: true
description: Trait contract name
schema:
type: string
- name: trait_name
in: path
required: true
description: Trait name
schema:
type: string
- name: tip
in: query
schema:
type: string
description: The Stacks chain tip to query from
94 changes: 94 additions & 0 deletions src/net/http.rs
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,8 @@ use std::time::SystemTime;
use time;

use chainstate::burn::ConsensusHash;
use net::Error::ClarityError;
use vm::types::{StandardPrincipalData, TraitIdentifier};

lazy_static! {
static ref PATH_GETINFO: Regex = Regex::new(r#"^/v2/info$"#).unwrap();
Expand Down Expand Up @@ -129,6 +131,11 @@ lazy_static! {
*STANDARD_PRINCIPAL_REGEX, *CONTRACT_NAME_REGEX
))
.unwrap();
static ref PATH_GET_IS_TRAIT_IMPLEMENTED: Regex = Regex::new(&format!(
"^/v2/traits/(?P<address>{})/(?P<contract>{})/(?P<traitContractAddr>{})/(?P<traitContractName>{})/(?P<traitName>{})$",
*STANDARD_PRINCIPAL_REGEX, *CONTRACT_NAME_REGEX, *STANDARD_PRINCIPAL_REGEX, *CONTRACT_NAME_REGEX, *CLARITY_NAME_REGEX
))
.unwrap();
static ref PATH_GET_CONTRACT_ABI: Regex = Regex::new(&format!(
"^/v2/contracts/interface/(?P<address>{})/(?P<contract>{})$",
*STANDARD_PRINCIPAL_REGEX, *CONTRACT_NAME_REGEX
Expand Down Expand Up @@ -1503,6 +1510,11 @@ impl HttpRequestType {
&PATH_GET_CONTRACT_SRC,
&HttpRequestType::parse_get_contract_source,
),
(
"GET",
&PATH_GET_IS_TRAIT_IMPLEMENTED,
&HttpRequestType::parse_get_is_trait_implemented,
),
(
"GET",
&PATH_GET_CONTRACT_ABI,
Expand Down Expand Up @@ -1870,6 +1882,45 @@ impl HttpRequestType {
)
}

fn parse_get_is_trait_implemented<R: Read>(
_protocol: &mut StacksHttp,
preamble: &HttpRequestPreamble,
captures: &Captures,
query: Option<&str>,
_fd: &mut R,
) -> Result<HttpRequestType, net_error> {
let tip = HttpRequestType::get_chain_tip_query(query);
if preamble.get_content_length() != 0 {
return Err(net_error::DeserializeError(
"Invalid Http request: expected 0-length body".to_string(),
));
}

let contract_addr = StacksAddress::from_string(&captures["address"]).ok_or_else(|| {
net_error::DeserializeError("Failed to parse contract address".into())
})?;
let contract_name = ContractName::try_from(captures["contract"].to_string())
.map_err(|_e| net_error::DeserializeError("Failed to parse contract name".into()))?;
let trait_name = ClarityName::try_from(captures["traitName"].to_string())
.map_err(|_e| net_error::DeserializeError("Failed to parse trait name".into()))?;
let trait_contract_addr = StacksAddress::from_string(&captures["traitContractAddr"])
.ok_or_else(|| net_error::DeserializeError("Failed to parse contract address".into()))?
.into();
let trait_contract_name = ContractName::try_from(captures["traitContractName"].to_string())
.map_err(|_e| {
net_error::DeserializeError("Failed to parse trait contract name".into())
})?;
let trait_id = TraitIdentifier::new(trait_contract_addr, trait_contract_name, trait_name);

Ok(HttpRequestType::GetIsTraitImplemented(
HttpRequestMetadata::from_preamble(preamble),
contract_addr,
contract_name,
trait_id,
tip,
))
}

fn parse_getblock<R: Read>(
_protocol: &mut StacksHttp,
preamble: &HttpRequestPreamble,
Expand Down Expand Up @@ -2349,6 +2400,7 @@ impl HttpRequestType {
HttpRequestType::GetTransferCost(ref md) => md,
HttpRequestType::GetContractABI(ref md, ..) => md,
HttpRequestType::GetContractSrc(ref md, ..) => md,
HttpRequestType::GetIsTraitImplemented(ref md, ..) => md,
HttpRequestType::CallReadOnlyFunction(ref md, ..) => md,
HttpRequestType::OptionsPreflight(ref md, ..) => md,
HttpRequestType::GetAttachmentsInv(ref md, ..) => md,
Expand All @@ -2375,6 +2427,7 @@ impl HttpRequestType {
HttpRequestType::GetTransferCost(ref mut md) => md,
HttpRequestType::GetContractABI(ref mut md, ..) => md,
HttpRequestType::GetContractSrc(ref mut md, ..) => md,
HttpRequestType::GetIsTraitImplemented(ref mut md, ..) => md,
HttpRequestType::CallReadOnlyFunction(ref mut md, ..) => md,
HttpRequestType::OptionsPreflight(ref mut md, ..) => md,
HttpRequestType::GetAttachmentsInv(ref mut md, ..) => md,
Expand Down Expand Up @@ -2463,6 +2516,21 @@ impl HttpRequestType {
contract_name.as_str(),
HttpRequestType::make_query_string(tip_opt.as_ref(), *with_proof)
),
HttpRequestType::GetIsTraitImplemented(
_,
contract_addr,
contract_name,
trait_id,
tip_opt,
) => format!(
"/v2/traits/{}/{}/{}/{}/{}{}",
contract_addr,
contract_name.as_str(),
trait_id.name.to_string(),
StacksAddress::from(trait_id.clone().contract_identifier.issuer),
trait_id.contract_identifier.name.as_str(),
HttpRequestType::make_query_string(tip_opt.as_ref(), true)
),
HttpRequestType::CallReadOnlyFunction(
_,
contract_addr,
Expand Down Expand Up @@ -2941,6 +3009,10 @@ impl HttpResponseType {
&PATH_GET_CONTRACT_SRC,
&HttpResponseType::parse_get_contract_src,
),
(
&PATH_GET_IS_TRAIT_IMPLEMENTED,
&HttpResponseType::parse_get_is_trait_implemented,
),
(
&PATH_GET_CONTRACT_ABI,
&HttpResponseType::parse_get_contract_abi,
Expand Down Expand Up @@ -3125,6 +3197,21 @@ impl HttpResponseType {
))
}

fn parse_get_is_trait_implemented<R: Read>(
_protocol: &mut StacksHttp,
request_version: HttpVersion,
preamble: &HttpResponsePreamble,
fd: &mut R,
len_hint: Option<usize>,
) -> Result<HttpResponseType, net_error> {
let src_data =
HttpResponseType::parse_json(preamble, fd, len_hint, MAX_MESSAGE_LEN as u64)?;
Ok(HttpResponseType::GetIsTraitImplemented(
HttpResponseMetadata::from_preamble(request_version, preamble),
src_data,
))
}

fn parse_get_contract_abi<R: Read>(
_protocol: &mut StacksHttp,
request_version: HttpVersion,
Expand Down Expand Up @@ -3362,6 +3449,7 @@ impl HttpResponseType {
HttpResponseType::GetAccount(ref md, _) => md,
HttpResponseType::GetContractABI(ref md, _) => md,
HttpResponseType::GetContractSrc(ref md, _) => md,
HttpResponseType::GetIsTraitImplemented(ref md, _) => md,
HttpResponseType::CallReadOnlyFunction(ref md, _) => md,
HttpResponseType::UnconfirmedTransaction(ref md, _) => md,
HttpResponseType::GetAttachment(ref md, _) => md,
Expand Down Expand Up @@ -3454,6 +3542,10 @@ impl HttpResponseType {
HttpResponsePreamble::ok_JSON_from_md(fd, md)?;
HttpResponseType::send_json(protocol, md, fd, data)?;
}
HttpResponseType::GetIsTraitImplemented(ref md, ref data) => {
HttpResponsePreamble::ok_JSON_from_md(fd, md)?;
HttpResponseType::send_json(protocol, md, fd, data)?;
}
HttpResponseType::TokenTransferCost(ref md, ref cost) => {
HttpResponsePreamble::ok_JSON_from_md(fd, md)?;
HttpResponseType::send_json(protocol, md, fd, cost)?;
Expand Down Expand Up @@ -3692,6 +3784,7 @@ impl MessageSequence for StacksHttpMessage {
HttpRequestType::GetTransferCost(_) => "HTTP(GetTransferCost)",
HttpRequestType::GetContractABI(..) => "HTTP(GetContractABI)",
HttpRequestType::GetContractSrc(..) => "HTTP(GetContractSrc)",
HttpRequestType::GetIsTraitImplemented(..) => "HTTP(GetIsTraitImplemented)",
HttpRequestType::CallReadOnlyFunction(..) => "HTTP(CallReadOnlyFunction)",
HttpRequestType::GetAttachment(..) => "HTTP(GetAttachment)",
HttpRequestType::GetAttachmentsInv(..) => "HTTP(GetAttachmentsInv)",
Expand All @@ -3704,6 +3797,7 @@ impl MessageSequence for StacksHttpMessage {
HttpResponseType::GetAccount(_, _) => "HTTP(GetAccount)",
HttpResponseType::GetContractABI(..) => "HTTP(GetContractABI)",
HttpResponseType::GetContractSrc(..) => "HTTP(GetContractSrc)",
HttpResponseType::GetIsTraitImplemented(..) => "HTTP(GetIsTraitImplemented)",
HttpResponseType::CallReadOnlyFunction(..) => "HTTP(CallReadOnlyFunction)",
HttpResponseType::GetAttachment(_, _) => "HTTP(GetAttachment)",
HttpResponseType::GetAttachmentsInv(_, _) => "HTTP(GetAttachmentsInv)",
Expand Down
14 changes: 14 additions & 0 deletions src/net/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1099,6 +1099,11 @@ pub struct ContractSrcResponse {
pub marf_proof: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct GetIsTraitImplementedResponse {
pub is_implemented: bool,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CallReadOnlyResponse {
pub okay: bool,
Expand Down Expand Up @@ -1288,6 +1293,13 @@ pub enum HttpRequestType {
OptionsPreflight(HttpRequestMetadata, String),
GetAttachment(HttpRequestMetadata, Hash160),
GetAttachmentsInv(HttpRequestMetadata, Option<StacksBlockId>, HashSet<u32>),
GetIsTraitImplemented(
HttpRequestMetadata,
StacksAddress,
ContractName,
TraitIdentifier,
Option<StacksBlockId>,
),
/// catch-all for any errors we should surface from parsing
ClientError(HttpRequestMetadata, ClientError),
}
Expand Down Expand Up @@ -1378,6 +1390,7 @@ pub enum HttpResponseType {
GetAccount(HttpResponseMetadata, AccountEntryResponse),
GetContractABI(HttpResponseMetadata, ContractInterface),
GetContractSrc(HttpResponseMetadata, ContractSrcResponse),
GetIsTraitImplemented(HttpResponseMetadata, GetIsTraitImplementedResponse),
UnconfirmedTransaction(HttpResponseMetadata, UnconfirmedTransactionResponse),
GetAttachment(HttpResponseMetadata, GetAttachmentResponse),
GetAttachmentsInv(HttpResponseMetadata, GetAttachmentsInvResponse),
Expand Down Expand Up @@ -1508,6 +1521,7 @@ pub trait ProtocolFamily {
pub struct StacksP2P {}

pub use self::http::StacksHttp;
use vm::types::TraitIdentifier;

// an array in our protocol can't exceed this many items
pub const ARRAY_MAX_LEN: u32 = u32::max_value();
Expand Down
Loading