text:
Timing of finality of a transaction in Mainnet
Hello i am facing some troubles when moving from test-net to main-net, my transactions seems to have to wait a long time for being reflected in the explorer, also i can not do any more transactions until they appear in the explorer, yesterday I had to wait almost 10 minutes. Now I am waiting for more than half an hour! and i can not see my transaction in the explorer neither do any other transaction.
Everything works fine in test-net but on main-net things gets complicated, I have noticed that Nami Wallet and Yoroi work terrific, but sending my transactions from Blockfrost endpoint may be the thing that makes things slow,  Any suggestion?

Just be patient. This behavior is because these days the blockchain has been really saturated, 90-95%.
Additionally, today was the launch of Sundaeswap, that means, more saturation.
This also has an impact in the wallets, you can try CCVault
Your transactions can take 10 minutes or even more when the blockchain is saturated.

Yesterday i waited more than an hour..  went to sleep and only in the morning i could see my transaction today i sent one transaction 3 hours ago... i have the hash 95653ab27d3467908945e21e09efc7d90bff72854f09b9ad969db03a17f8fa37 but.. now 3 hours later i can not see it in the explorer.

Yes, that's the reason this year Cardano will scale: https://iohk.io/en/blog/posts/2022/01/14/how-we-re-scaling-cardano-in-2022/

i have waited 9 hours! today :(

That's too much, I minted an NFT three hours ago, it took like 10 minutes. Try another wallet, CCVault seems to be performing better these days.

I was using blockfronst SendTx Endpoint no browser wallet

now i am getting this error: BlockfrostServerError: Mempool is full, please try resubmitting again later.
but the first was submited so it is not related to blockfrost only but to thw whole blockchain.

Here is a nice tweet with an explanation from Alessadro: https://twitter.com/berry_ales/status/1485198340698562563?t=C3pw53AusKAEcitlLfnpbg&s=09

The blocks are much more saturated on mainnet. It's normal to wait 5-10 minutes for a transaction to get into the block chain when the blocks are saturated.

Yesterday i waited more than an hour..  went to sleep and only in the morning i could see my transaction today i sent one transaction 3 hours age... i have the hash 95653ab27d3467908945e21e09efc7d90bff72854f09b9ad969db03a17f8fa37 but.. now 3 hours later i can not see it in the explorer.

Some wallets are better than others with dealing with the backlog.


text:
.NET cardano-cli query utxo Process freezes on a specific address
I have a strange situation where running the cli from a .net Process.Start() it works all of the time (on tested addresses), but on 1 address it just freezes - process.WaitForExit() never exits.
When the cli is run from the command line - I get all results as expected. Pretty sure this is something with Process.Start(), but for the life of me I can't figure it out.
Addresses below
Works (Arguments) - has about 8 UTXOs
query utxo --address addr_test1qz065xj60utnn4d0wmnc3aqt84w73vwlegmpves5v8pyrh5mm26227qq66j3uzr38xn5gy9swm7h4g3lxu8u0nqzddjquz6fqm  --testnet-magic 1097911063

Locks up (Arguments) - has about 40 UTXOs
query utxo --address addr_test1qz7mvmykanj59dz49ef5lvvn0yymmsj77w2pjfynkf3an2vq3jtd2jajxyfylhvpxskdyeum4s6rr4x08kl28r4hc72sskhe6g  --testnet-magic 1097911063

Also I know this should be an async function - but I'll sort that later ;-)
public CardanoCliResult Cli(List<string> arguments, bool useNetwork = false, bool useEra = false) {
    if (useNetwork) arguments.Add($" {_network}");
    if (useEra) arguments.Add($" {_era}");
    ProcessStartInfo start = new ProcessStartInfo() {
        FileName = _cli,
        Arguments = string.Join(" ", arguments),
        UseShellExecute = false,
        RedirectStandardOutput = true,
        RedirectStandardError = true,
        CreateNoWindow = true,
    };
    start.EnvironmentVariables["CARDANO_NODE_SOCKET_PATH"] = _socket;

    var process = Process.Start(start);
    process.WaitForExit(); <<<<------ Locks up here
    var result = new CardanoCliResult() {
        Command = $"{_cli} {string.Join(Environment.NewLine, arguments)}{Environment.NewLine}",
        Ok = process.ExitCode == 0,
        Error = process.StandardError.ReadToEnd().Trim(),
        Output = process.StandardOutput.ReadToEnd().Trim()
    };
    ConsoleUpdateCli(result);
    return result;
}

If anyone has an idea or has seen this before, any help would be great
Thanks

Solution I found at https://docs.microsoft.com/en-us/dotnet/api/system.diagnostics.processstartinfo.redirectstandardoutput?view=net-5.0:
var process = Process.Start(start);
string so = process.StandardOutput.ReadToEnd();
string se = process.StandardError.ReadToEnd();
process.WaitForExit();

Hopefully it stays working

Ok - I think I have the solution
https://docs.microsoft.com/en-us/dotnet/api/system.diagnostics.processstartinfo.redirectstandardoutput?view=net-5.0
You need to read the output before you wait - who knew ;-).

I found the answer - read the output before the wait
var process = Process.Start(start);
string so = process.StandardOutput.ReadToEnd();
string se = process.StandardError.ReadToEnd();
process.WaitForExit();

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

sort: votes


text:
Metadata value limits (64 UTF bytes) - Use Arrays ? NFT image question
I'm currently setting up my minting software and noticed I get the error when assigning a CIDv1 hash as the image (CIDv0 works fine - it just fits)"Text string metadata value must consist of at most 64 UTF8 bytes"
I also noticed that someone got around this by splitting it up into a list of less than 64 bytes each.
eg.
{...image: [ "lessthan64string-0", "lessthan64string-1", "lessthan64string-2", "lessthan64string-3" ]...}
= lessthan64string-0lessthan64string-1lessthan64string-2lessthan64string-3
This seems very off standard for a NFT or am I wrong. Obviously you can recreate the string by joining, but I wouldn't think the chances of market places doing that is big.
I've had a look at - https://github.com/cardano-foundation/CIPs/pull/85, but I'm not sure about it.
If anyone could point me the the direction of what is the proper way to di this - It would be muchly appreciated
Thanks for your time
FYI: the reason for the CIDv1 is I am using https://nft.storage/ (as well as pinata) and I want the 2 hashes to match for longevity of the NFT for the images and they seem to only support CIDv1 - and it's going to have to be supported at some stage. The filecoin (nft.storage) one will be used as a backup

I would store the CIDv0 in the metadata. You should be able to convert from v1 to v0 if it's using v1 protocol buffer codec.
# If this outputs "protobuf" we can be reasonably certain we can convert
ipfs cid format -f "%c" -b base58btc bafybeiccuppnh2nh54jtubqo2jjmngzlnnmliejjq3xlswxzh24et2llu4
# Convert our CIDv1 to CIDv0 (returns "QmSpnYb3romJejsUqhRepYr6GBwuKUFj1kqrhtk1z2Hn8E")
ipfs cid format -f "%M" -b base58btc bafybeiccuppnh2nh54jtubqo2jjmngzlnnmliejjq3xlswxzh24et2llu4

Source: https://discuss.ipfs.io/t/make-cidv0-from-cidv1-using-cid-ipfs-io/10647/2

Thanks for the comment - I'll see what I can do :-)

Storing the longer image url as an array is also in-line with the CIP standard. If you use CIDv1 and store it as an ipfs url split in two, it should work and is supported by pool.pm and other NFT viewers out there.

@AndrewWestberg-BCSH can you elaborate on this pls? how is this done?

@rx2347 To store it as an array, just do
"image": [ "first part of the url", "second part of the url"]

@AndrewWestberg-BCSH so I just split the url string at a random character? thats so weird...

@rx2347 as long as each part is less than 64 chars, anybody implementing the NFT metadata spec just concatenates them together.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Programmatically write and submit a smart contract
Title. Any ways to accomplish this? Preferrably in react/javascript
Edit: downvote me to oblivion!!

To avoid being downvoted, try to add more detail to your question instead of just writing "Title". If you post a vague question, you'll most likely only get a vague answer.

You can use plu-ts to create a smart contract in Typescript, and then use Mesh (Web3 SDK) in your React project to interact with the Smart Contract.


text:
Best practice for testing smart contract
Let's say you have your haskell code ready to test as a smart contract on the testnet, what is the best practice to go about testing if your smart contract works as intended? Does the same process work for the mainnet?
Thanks, Myles

This question is too broad. It really depends on the use case you are using the smart contract for. It is like asking what are best practices to test software.
Mainnet and testnet are just different networks, the smart contacts works the same way on both.


text:
cardano-cli transaction submit example with native assets
I'm having trouble using the cardano-cli to send one tx. I have one address with 9 ADA and 10,000,000 each of two tokens with the same minting policy and I want to send 5,000,000 ADA of each token to a foreign address which has 10 ADA and no tokens.
For example
Address that has the native assets I want to send:
TxHash: 123456789123465
TxIx: 0
Amount: 9000000 lovelace + 10000000 1234567891234.token1 + 10000000 1234567891234.token2 + TxOutDatumHashNone
Address which I want to send native assets to:
TxHash: 123456789123456
TxIx: 0
Amount: 10000000
What commands/steps exactly are needed using the cardano-cli from here in order to accomplish sending 5,000,000 of each native token?
Thanks, Myles

First thing to note, you can only send to an address, not a txhash. Can you also provide what commands you've tried already and what error occurs when doing so?

MY_ADDR=addr_test1qzl6m...
#Send lovelace change to my address
CHANGE_ADDR=$MY_ADDR
MY_UTXO_IN=123456789123465#0
RECEPIENT_ADDR=addr_test1...

# Build tx
cardano_cli transaction build \
--alonzo-era \
--tx-in $MY_UTXO_IN \
--tx-out $RECEPIENT_ADDR+9000000+"10000000 1234567891234.token1"+"10000000 1234567891234.token2") \
--change-address $CHANGE_ADDR \
--testnet-magic 1097911063 \
--out-file tx.build

If you have change in native tokens then you need to add another --tx-out to return to your address for example:
TOKEN1_CHANGE=1000
TOKEN2_CHNAGE=2000
--tx-out $CHANGE_ADDR+1400000+"$TOKEN1_CHANGE 1234567891234.token1"+"$TOKEN2_CHANGE 1234567891234.token2"

Sign and submit
# Sign tx
echo "Sign Tx ..."
cardano_cli transaction sign \
--signing-key-file my_payment.skey \
--tx-body-file tx.build \
--out-file tx.sign
echo "Done."

# Submit tx
echo "Submiting Tx ..."
cardano-cli transaction submit --testnet-magic 1097911063 --tx-file tx.sign

Here you can find various examples for sending token and other stuff https://github.com/invictusappscom/cardano-terminal-wallet especially this script https://github.com/invictusappscom/cardano-terminal-wallet/blob/master/send-token.sh


text:
Identifying node locations by region
I want to operate stake pool nodes in underserved areas. My cloud provider automatically chooses the cheapest datacenter nearest to me. But I am willing to pay more to deploy to data centers in underdeveloped countries.
How can I identify which regions are saturated and which regions have little or no nearby connectivity?
The IOHK Shelley node map, is the best I have found, but it looks hard to interpret. I came away thinking half the nodes are in the ocean.
Yes, it was...

Mobile is bunked. But if there’s something in particular besides boilerplate Good Question stuff I’m not sure what you mean. I want to operate a staking pool where there are few to none, how can I spin up some nodes with in underserved areas?

Are you talking about staking in under-served locations?  It would also be a good idea to take a look at [ask] for guidance on improving your question.

I mean there are no links to the docs on mobile.

Yeah I definitely did a couple of searches. I think participating in the network health is on topic. Thank you for the link

what was wrong with my question? it has 86% upvote  standing on r/cardano.

This is not r/Cardano and has a clear mission to provide mostly fact based, enduring, clear and concise answers to Cardano questions.  Take a look at [so] and [se] for the direction this site needs to head in the long run.

Seems like a waste of time. Just fix it for me. I really don't know what you want.

Thank you, gRebel. Let's reset. :)

Reddit variety understood the pasta.
PoolGermany says:

There are some maps:
https://www.adatainment.com/index.php?page=pool_map
https://poolpeek.com/poolpeek.com/poolsearchmap
https://monadpool.com/cardano.html
Enjoy! :)

https://adatools.io/hologram only slightly helpful. But adatainment allows one to drill down on to staking pools to see where they are on a political map.
I don't think any of these are exhaustive.


text:
Can I avoid using a public IP on Block-Producer (BP) node?
My BP and relays are on the same local subnet, I would prefer to give them the private IP address in the topology files.
However, all of the guides I've come across explicitly state using public IPs. Is there a problem with using private IPs in the topology files to connect my BP node and my relay nodes?

Each of your Cardano nodes needs a static IP address to communicate between each other. You can use IP or domain names.
Block Producer (BP) node
For better security, you can choose to set a private IP to your BP node to communicate with your relays (on the same private network) since your BP is hosting sensitive data you don't really want to expose.
Relay nodes
However, it is necessary that the relay nodes have a public IP address as the other external relay servers will need to establish incoming TCP/IP connections with yours to exchange and update informations.
You can set 1 public IP address for each one of your relays but you can also use a single public IP address and port-forward to share with your relays.

Hi @Bao, thank you for the feedback. I guess I was wondering why I would ever use the BP's public IP if I didn't need to, and I don't really see a need to.

As long as your BP can communicate with your relays, it is not required to have a public IP address on your BP. But your relays will need at least 1 public IP to receive incoming TCP/IP connections.

Great that’s all I need to hear, thank you

I dont know how you manage your nodes :)
but for security reasons, i would recommend to use another node, which will be the "Jump-Server".
this Jump-Server has a public_IP, which will be used for you to connect with ssh, and only this system will have access to connect with ssh to the rest of your nodes (BP and Relays)


text:
What's NODE ID? I'm not talking about pool ID
Was setting up script, sendmytip.sh, to update PoolTool with tip and height information.
I noticed this NODE_ID value:
#!/usr/bin/env bash

## CHANGE THESE TO SUITE YOUR POOL

# your pool id as on the explorer
PT_MY_POOL_ID="xxxx"
# get this from your account profile page on pooltool website
PT_MY_API_KEY="xxxx-xx-xx-xx-xxxx"
# Your node ID (optional, this is reserved for future use and is not captured yet)
PT_MY_NODE_ID="xxxx-xxx-xxx-xxx-xxxx"

It's the last line, and is clearly different from the Pool ID.
Would anyone care to let me know how to find a node id, or explain what they are?
When i read a spec, interface, or proposal, however vague readers are giving a clue. I ask because I did not find one. Interfaces aren’t even told how to handle the property.

As mentioned, the node ID is a variable that has not yet been implemented on Pooltool side so just ignore it at the moment.
Date : September 26th, 2021
As there is no mention of this variable yet in the Pooltool official documentation, one can "assume" that this would be an unique ID to identify each relay node of your pool ID? (would it make sense?)

Thank you, and for all: please don’t downvote in event question has authoritative answer. It is server a purpose until then.


text:
Verifying Payment Address
Before funding the payment address on my staking pool, I would like to make sure that the funds can be retrieved by me, as the process of air gapping to create these series of keys and addresses introduces many opportunities for human error.
Would you please let me know if I can use cardano-cli or some other method to ensure the funds won't be lost once sending?
As a sanity-check, I sent a 1 ADA transaction back to my funding source to ensure things were okay. But I would still like a simpler way of checking that my keys are all in line.

To make a long story short, in Cardano's environment, you will need 2 sets of keys. One set to control your funds (send and receive $ADA and tokens) and one other set to control your staking activities (to participate in the protocol delegating your ADA to a stake pool or to earn rewards by operating your own stake pool).
These 2 set of keys will allow you to generate a payment address or a stake address or both meaning a payment address with "staking capacity".
As long as you keep these 2 sets of keys (payment keys and stake keys) in a safe and secured place, it's OK you will be able to have access to your funds.
It is recommended to generate these 2 sets of keys on an offline machine to minimize the risk of hack.
Generate your payment keys pair (payment.skey and payment.vkey):
cardano-cli address key-gen \
--verification-key-file payment.vkey \
--signing-key-file payment.skey

Generate your stake keys pair (stake.skey and stake.vkey):
cardano-cli stake-address key-gen \
--verification-key-file stake.vkey \
--signing-key-file stake.skey

Now for your stake pool, you will need a "payment address with stake capacity" so first we will generate a stake address and then a payment address that can delegate to the stake address.
Generate your stake address from the stake address verification key and store it in stake.addr
cardano-cli stake-address build \
--stake-verification-key-file stake.vkey \
--out-file stake.addr \
--mainnet

Finally, create this "payment address with stake capacity"
cardano-cli address build \
--payment-verification-key-file payment.vkey \
--stake-verification-key-file stake.vkey \
--out-file payment.addr \
--mainnet

That's it, now you can do whatever you want with these addresses as long as you keep your 2 sets of keys safe just for you... (especially the payment keys)
However, if you are too stressed, you can send 1 ADA to this address and then send it back with a simple transaction to make sure you have mastered the process.
You can follow this tutorial to understand how to forge and sign a simple transaction by following the instructions in this official video.
Good luck.

I actually made a typo and worried that i overwrote a private key for the payment address, after I had already staked everything. Some times human error is all it takes, fortunately there are snapshots.

This was a very good explanation, thank you!

If you overwrote by mistake your private key, well... you shouldn't have done it. It is impossible for the signing key (payment.skey) to be deduced, extracted or reverse engineered from the payment.addr. it's a kind of mathematical function that only goes in a single direction.  Just make sure that pairing between the payment address and its corresponding payment key is strict.


text:
What Utility Do Third-Party Services Provide with Undisclosed Slot Lottery Information?
Small Sample of Concerns Belonging to Larger Family of Unknown Real or Figurative Concerns
I would like to send my predetermined Slot Leader reports to PoolTool, yet I only use the API key they provide for sending tip heights.
What happens when they know I won the slot lottery? At first I was very paranoid and could only imagine slot leader, even when plural for a single slot, is private information not for public disclosure. But aha, it's not! At least I am unable to find it on PoolTool after a reasonable search.
Worse though, it's not public and not private, so it's valuable information in the hands of a privileged few, or so I thought to myself. My reasoning being if I am an SPO with a relay or two, and the Whales and pre-AML/KYC bullies are around, it would be trivial to assault my nodes, and also interesting:

Can we force a Slot Leader to fail to forge with a given attack that is cheap enough to put me back in the lottery for that slot? DDoS cheap, for example.
Is this easier when colluding with other giants?
Could small SPOs be denied the ability to mint new blocks in the worst case scenario of mass-collusion scenarios where the at least one of the collaborators would have a better chance at being the slot leader than they did if they were to do nothing.

Effect on Operator Behavior
So I never reported, yet I still missed two blocks when I was slot leader anyway. Now that I've probably figured out the network issues causes this, I will report my slot, just because, why not?
But still, what utility is being served by conceding privileged information to a community member, which means many things from competitor to valued contributor, but still a private third-party.
Bounty Will Likely Not Be Rewarded Within Seven Days
I am asking for a canonical answer. @Anton, tried to derive one, but I see holes that I can comment on later.
Therefore, I will delegate to the answers I find interesting, thought-provoking, reasonable-yet-contradicting, and so on; just ones I personally found valuable. I encourage you to do the same.
Upvote and ADA-only Recipients
So far these are those delegators, with the first satisfying all of the listed qualities.

Ticker: SNOWY for Anton's Answer - OP comments,

"having the previous slot would be quite the computational challenge
alone, and it does take days or weeks for those pages to populate, but
they don't show a decision tree for a slot battle–maybe a deceptive
illustration of 3,100 pools POSTing (every second as required) its Tip Height API
endpoint, which does some processing on before responding to the POST. Like
wanting to know which node your running, if it's a release or dev
build, other things it must record before responding. It does not
report a Slot Battle diagram based on what delegators are
reporting to relays and other delegators. I don't even think it
asks if a delegator is saying it is the Slot Leader.
The API has nine endpoints, but Amazon masks their location, claiming
they are all in the US. But they appear to be AWS CloudFront "Web 3.0"
CDNs, and that a show of good faith if CloudFront was chosen for its
equal access to low-latencies ambitions:

> To deliver content to end users with lower latency, Amazon CloudFront
> uses a global network of 275+ Points of Presence (265+ Edge locations
> and 13 regional mid-tier caches) in 90+ cities across 47
> countries. Amazon CloudFront Edge locations are located in:

"Looks nice, but you can't know where they are. You can experiment,
but if you just want gains you don't experiment, you stake in the most
developed of Western Europe, hedging in the coasts of the US, because
it had had an inflation clock downtown from me since before I was
born, and the world likes it that way. AAA debt for sale for almost
all of me and that clock's life, ala CIA and USN, and so on."
"Meanwhile, the orphan graph reminds me of a PoolTool page, or the
other way around..."
[Middle Finger Emoji to almost every stake holder]
"Okay, I'll lay off pooltool, or why it doesn't report past slot
leader, leader arrays, empty slots, or pull from the verbose as the
need for a reconstructed Globe Theater."
What if you just need 51% of topology pathfinders to agree that your
AWS CloudFront WebAPI is gospel? You'd make a topologyUpdater script
that basically reinforced this Western exploit attacking the
single-second slot. Sites like PoolVet claiming if you don't
comply, go let the Best Practices Group promote gain over virtue.

"And on and on," he continued ranting.
"Where's the utility? What's this project really about?"

I didn't realize you could send your slot leader reports. I am doing the tip heights but not slot leader. Can you add a link where you found out how to do that as well as view that? I would think this would be something you wouldn't want public based off what you've stated above.

Yes, there's a talented group that builds tools for the community. Many actually. They range from sites (graph explorers, big data, etc), to various niches like Pool Operator tools. They are well rewarded for the hours on ongoing OSS work. As an example, one tool was communally improved into a pretty polished piece of SPO software, it can tell you your block slots, if any, in the current, previous and next epoch. This isn't magic, IOHK goes out of its way to use English with equations. But forgive me if I failed, I cannot find the discussion about private centralized Slot Leader databases.

I had to do a lot of digging but this is what I have came up with. Please correct me if any of this is incorrect and I'll update the answer.
What happens when they [PoolTool] know I won the slot lottery?
After going through the CNCLI documentation, it looks like the intention is to only ever send the Current and Previous slot leader. Furthermore, when I look at the json result for a LeaderLog, it returns the "slot", the "slotInEpoch" and an "at" which is a date time. Based off knowing this payload as well as the intended use, I am guessing they are using it to fill in the Orphans section of the site before rewards are calculated. Looking at a couple of examples, I am only seeing Orphans 3 to 4 Epochs back (so 297/298). I believe with these logs they could fill in more realtime.
Can we force a Slot Leader to fail to forge with a given attack that is cheap enough to put me back in the lottery for that slot? DDoS cheap, for example.
If you could keep the relays down long enough for another slot leader to propagate, then yes you could. If the pool is protecting against DDOS/DOS attacks, then this is probably unlikely to work.
Is this easier when colluding with other giants?
If you were a pool like Binance, with 42 saturated pools, then you could potentially cause issues for other SPOs by denying them in your topology files. This could potentially cause issues for their propagation. (Still a big if). The other would be a 51% attack if you got enough people to join you. This would be extremely unlikely to happen though.
Could small SPOs be denied the ability to mint new blocks in the worst case scenario of mass-collusion scenarios where the at least one of the collaborators would have a better chance at being the slot leader than they did if they were to do nothing.
Short answer yes but it would likely be a very small effect. The example would be the Binance one above. This also could be worse if the pool has no protection against DDOS type attacks.
What utility is being served by conceding privileged information to a community member, which means many things from competitor to valued contributor, but still a private third-party.
I believe the utility would be keeping a more up-to-date Orphaned block tab for PoolTool. In general, it would be statistical.
I hope this is helpful.

Something that could be done is to ask stake pool operators to report just the number of blocks they have been awarded for the next epoch.  They could report this just prior to the start of the epoch.
If a pool operator chooses to report his number of slots awarded then he would be incentivised to report the correct number.
He must tell the truth because if he lied by reporting just one less than the actual number, he will be found out if/when his pool successfully produces all its blocks.  Maybe occasionally his pool will lose a block to a slot battle etc. but mostly it will produce all the blocks issued and then if he lied by saying less then everyone will know.  He will then lose trust with the community.
I don't think reporting slots issued like this would create a security concern because no one would know the actual timing of the slots issued except for the pool operator himself.  Even knowing the precise number of slots awarded doesn't reveal anything much since this amount can be approximated simply by looking at the total amount staked at his pool.
I did think about sending abridged slot leader reports like this but didn't look into where to send this information.  I certainly formed the opinion that there was no way that I was going to send the full slot leader reports containing the timing because, as you say, that would provide timing information to potential attackers.

Please correct me if I'm wrong, but I think this is a non-issue if you don't send upcoming slots/the slot leader schedule, but use the Sendslots command instead:
CNCLI does not send the slot number and/or date and time of the blocks you are assigned to mint. Straight from the CNCLI Git:

Sendslots command
The sendslots command securely sends pooltool the number of slots you
have assigned for an epoch and validates the correctness of your past
epochs. You must have a synchronized cncli.db database and have
calculated leader logs for every pool in pooltool.json before calling
this command. It should be called within the first 10 minutes of the
epoch cutover.

Here is an example:

2020-12-01T03:34:33.883Z INFO  cncli::nodeclient::leaderlog > Sending:
{"apiKey":"blah-blah-blah","poolId":"00beef0a9be2f6d897ed24a613cf547bb20cd282a04edfc53d477114","epoch":232,"slotQty":25,"hash":"d15b6c8d4c81fe48cff0650c5b59ab20da9765374c58c933dacd058eb38bb670"}
2020-12-01T03:34:33.969Z INFO  cncli::nodeclient::leaderlog > Pooltool
Response:
{"statusCode":200,"headers":{"Content-Type":"application/json","Access-Control-Allow-Origin":"*"},"body":"{"success":true,"message":"We have updated your assigned slots for epoch 232 to be 25 with a hash of
d15b6c8d4c81fe48cff0650c5b59ab20da9765374c58c933dacd058eb38bb670.  You
must provide an array of slots that matches this hash to have your
performance counted."}"}

So as I understand, pooltool does not know which slots you are assigned to and they can't find out based on the info CNCLI sends to them.


text:
Setting up a stake pool relay node
I am in the initial steps of creating a stake pool and I've learnt that I need a block producer and a relay node. For the process of getting AWS instances, I would like to know:

Do I need two relay nodes?
Are the server requirements for a relay node the same as those of a block producer?
For a start, is there a specific pledge amount with no delegators yet, that would have chances of producing a block?

You do not need two relays nodes, in fact, you do not need even a relay, but it is a recommended practice.
Yes, the requirement is for the cardano-node and it is same being a relay, as well as a block producer.
Right now, you need little bit more than 1M ADA to mint a block.

Here are some directions that might help you move forward
1. Do I need 2 relay nodes?
It is not necessary to have two relay nodes but each stake pool must run at least one block-producing node and one relay node. The block-producing node holds the keys and certificates necessary to issue blocks and rewards payments, but it should not be directly connected to the network because you don't want to be exposed.
For security reasons, it must be connected only to one or more relay nodes controlled by the stake pool operator. Then, the relay nodes connect to other relays on the network. This setup is configured in the topology.json file.
2. Are the server requirements for a relay node the same as those of a block producer?
Officially, the minimum required is the same for a BP and a relay node. However, from my personal experience with equivalent servers the relays consume on average slightly more RAM.

3. For a start, is there a specific pledge amount with no delegators yet, that would have chances of producing a block?

You need to have 500 ADA for the pool deposit
It is not a question of knowing if you are going to produce a block
or not for such or such amount of stake/pledge but rather to know how often?
With 100k ADA your pool will produce about 7 blocks per year. You can take 5 minutes to read this interesting thread "Actual Cost to Operate vs Actual Returns thoughts?" on the official Cardano forum.


text:
Failing Validation on Script Address
I am trying to unlock an NFT that I locked into a script address. The unlocking succeds when I have some basic validation  rules but when I add the minterIsPaid rule below, the validitation transaction fails.
data AssetPurchase = AssetPurchase {
    nft :: !TokenName
   ,minter :: !Address
   ,minterCurrency :: !AssetClass
   ,minterAmount :: !Integer
   ,beneficiary :: !Address
   ,beneficiaryAmount :: !Integer
   ,beneficiaryCurrency :: !AssetClass
   ,collateral :: !AssetClass
   ,collateralAmnt :: !Integer
} deriving (Show, Generic, FromJSON, ToJSON)

purchaseValidator :: AssetPurchase -> () -> () -> ScriptContext -> Bool
purchaseValidator p () () ctx  = validate
    where
        validate ::  Bool
        validate =   validateTxOuts && minterIsPaid

         minterIsPaid :: Bool
         minterIsPaid = assetClassValueOf (valuePaidToAddress (minter
                        p)) (minterCurrency p) == minterAmount p

         valuePaidToAddress :: Address -> Value
         valuePaidToAddress addr = mconcat (fmap txOutValue (filter
                     (\x -> txOutAddress x == addr) (txInfoOutputs
                     (scriptContextTxInfo ctx))))
...

My parameters for deploying this contract look like this:
writeAssetPurchaseValidator = writeValidator "token/lock/mds-lock.plutus" $ validator $ AssetPurchase
                                {
                                    nft= Ledger.Value.tokenName $ TE.encodeUtf8 $ T.pack "MediSnap#06"
                                   ,minter = L.pubKeyHashAddress (L.PaymentPubKeyHash $  L.PubKeyHash $ BuiltinByteString $  TE.encodeUtf8 $ T.pack "bebe8013168a1f3607bddb3a170b0adb12400316a8bcf34b7efedf0a") Nothing
                                   ,minterCurrency = Ledger.Value.assetClass (Ledger.Value.currencySymbol $ TE.encodeUtf8 $ T.pack "") (Ledger.Value.tokenName  $ TE.encodeUtf8 $ T.pack "")
                                   ,minterAmount = 2000000
                                   ,beneficiary = L.pubKeyHashAddress (L.PaymentPubKeyHash $  L.PubKeyHash $ BuiltinByteString $  TE.encodeUtf8 $ T.pack "482421baa0219f801aa40f91dd8ec5d6ded4631a73f09b9d9b29848c") Nothing
                                   ,beneficiaryCurrency = Ledger.Value.assetClass (Ledger.Value.currencySymbol $ TE.encodeUtf8 $ T.pack "") (Ledger.Value.tokenName  $ TE.encodeUtf8 $ T.pack "")
                                   ,beneficiaryAmount = 2000000
                                   ,collateral = Ledger.Value.assetClass (Ledger.Value.currencySymbol $ TE.encodeUtf8 $ T.pack "") (Ledger.Value.tokenName $ TE.encodeUtf8 $ T.pack "")
                                   ,collateralAmnt = 2000000
                                }

My unlocking transaction is as shown:
cardano-cli transaction build-raw \
     --babbage-era \
    --tx-in 05be931d5f807650412724cb75faa7da3c898ccbeddd5b762dc8480b12ca6875#0 \
    --tx-in-datum-file "../token/lock/unit.json" \
    --tx-in-redeemer-file "../token/lock/unit.json" \
    --tx-in-script-file "../token/lock/mds-lock.plutus" \
    --tx-out $(cat ../wallets/buyer/buyer.addr)+"2130271 lovelace + 1 6669034a6d4719d62097b5ed28f81e76b80ca2a289d9a4aceabc38d2.4d656469536e61702336" \
    --tx-out $(cat ../wallets/beneficiary/beneficiary.addr)+2000000 \
    --tx-out $(cat ../wallets/minter/minter.addr)+2000000 \
    --tx-in-collateral "dc6fba11e10917236072a200c5e9e8b2c5c95d317d9b924bd736952fb5153c39#0" \
    --tx-in-execution-units="(10000000000, 14000000)" \
    --protocol-params-file "../token/lock/protocol-params.json" \
    --fee 1869729  \
    --out-file "../token/unlock/tx.body"

cardano-cli transaction sign \
    --tx-body-file "../token/unlock/tx.body" \
    --signing-key-file "../wallets/buyer/buyer.skey" \
    --$TS \
    --out-file "../token/unlock/tx.signed"

When I run this unlock transaction, I get an error which is not very helpful.
The error is:\n
CekError An error has occurred:  User error:\nThe machine terminated because of an error, either from a built-in function or from an explicit use of 'error'.
Command failed: transaction submit  Error: Error while submitting tx: ShelleyTxValidationError ShelleyBasedEraBabbage (ApplyTxError [UtxowFailure (UtxoFailure (FromAlonzoUtxoFail (UtxosFailure (ValidationTagMismatch (IsValid True) (FailedUnexpectedly (PlutusFailure "\nThe 3 arg plutus script (PlutusScript PlutusV1 ScriptHash \"a83254bf933b34d7d0072c3270a07cf1d9c87d34b01ffdf8ae29d959\") fails.\nCekError An error has occurred:  User error:\nThe machine terminated because of an error, either from a built-in function or from an explicit use of 'error'.\nThe protocol version is: ProtVer {pvMajor = 7, pvMinor = 0}\nThe data is: Constr 0 []\nThe redeemer is: Constr 0 []\nThe context is:\nPurpose: Spending (TxOutRef {txOutRefId = 05be931d5f807650412724cb75faa7da3c898ccbeddd5b762dc8480b12ca6875, txOutRefIdx = 0})\nTxInfo:\n  TxId: c5c5a5a47c7f3f204aafe3b2a2cea20ceb2fab7f1a0a3d162508ad0fe601b77d\n  Inputs: [ 05be931d5f807650412724cb75faa7da3c898ccbeddd5b762dc8480b12ca6875!0 -> - Value (Map [(,Map [(\"\",8000000)]),(6669034a6d4719d62097b5ed28f81e76b80ca2a289d9a4aceabc38d2,Map [(\"MediSnap#6\",1)])]) addressed to\n                                                                                ScriptCredential: a83254bf933b34d7d0072c3270a07cf1d9c87d34b01ffdf8ae29d959 (no staking credential) ]\n  Outputs: [ - Value (Map [(,Map [(\"\",2130271)]),(6669034a6d4719d62097b5ed28f81e76b80ca2a289d9a4aceabc38d2,Map [(\"MediSnap#6\",1)])]) addressed to\n               PubKeyCredential: 08498419e83871d01aae9c97a45218f3aedc0b963f787569ce0c1463 (no staking credential)\n           , - Value (Map [(,Map [(\"\",2000000)])]) addressed to\n               PubKeyCredential: 482421baa0219f801aa40f91dd8ec5d6ded4631a73f09b9d9b29848c (no staking credential)\n           , - Value (Map [(,Map [(\"\",2000000)])]) addressed to\n               PubKeyCredential: bebe8013168a1f3607bddb3a170b0adb12400316a8bcf34b7efedf0a (no staking credential) ]\n  Fee: Value (Map [(,Map [(\"\",1869729)])])\n  Value minted: Value (Map [])\n  DCerts: []\n  Wdrl: []\n  Valid range: (-\8734 , +\8734)\n  Signatories: []\n  Datums: [ ( 923918e403bf43c34b4ef6b48eb2ee04babed17320d8d1b9ff9ad086e86f44ec\n          , <> ) ]\n"
...
alot of text for datum hashes

Any ideas what could be goin wrong?

I've seen this message before [...] because of an error, either from a built-in function or from an explicit use of 'error' [...] when I tried running a Plutus v1 script with Plutus v2 context. Perhaps check if you're using any v1/v2 builtins unintentionally depending on your version choice.

Yep, checked all my imports, looks ok. All versioned imports have V1

First, try adding trace logs to your validator, i.e. use traceIfFalse with a unique message for each condition.
Then using cli's build cmd instead of build-raw. It runs script evaluation and prints trace log output on failure.

Nice. Adding the traceIfFalse and using build helped alot. From the error logs,  I got code PT5) and using (https://plutus.readthedocs.io/en/latest/troubleshooting.html#error-codes) ,I am thinking that the minterIsPaid function retuns a false. Now if only I can tell why..thanks!


text:
Does Cardano Node support chained transactions?
Does Cardano node supports processing of chained transactions?
E.g. we have an output [O1], and want to create a transaction [TX1] using [O1] as an input and creating new output [O2] and then, until [TX1] is confirmed in the network create [TX2] using [O2] as an input and creating new output [O3].

Is Cardano node capable of handling this chain [TX1, TX2] properly? It has to lookup [O2] in mempool in order to verify TX2 is valid.
Is it possible at all that [TX1, TX2] get into one block? Does the current block validation protocol allows that at all?

No - as it would also opens a web of security issues, including deficiencies of accounting model - also, it enables a possibility to DDoS network for a small duration.
*Correction: Apparently you can do this already, it is just not easily made available to end-user facing tools yet.

What security issues are you talking about exactly? Bitcoin and Ergo have been successfully supporting this feature for quite a long time already - and no significant vulnerabilities were found in this approach so far. So what's special about Cardano here?
As fo DDoS, I guess the network can be DDoSed anyway and tx chaining doesn't make much difference here.

Oh, that's great. Can you elaborate on how can I do that? It's ok to use any Haskell SDK for me.


text:
NFT royalties Cardano
I am attempting to create a NFT with % royalties when NFT is re-sold.
My idea would be the following :

The symbolic owner of the NFT is defined in the datum of the script e.g. datum = { owner : [ownerwallet] , ... }
The following end points are available in the smart contract :

A) purchase : if someone want to purchase the NFT (i.e. rename the owner par of the datum) B) define_selling_price : to define at which selling price the purchase operation will work  C) define_who_can_purchase: to ensure that if you want to sell it to someone, nobody else can purchase it (i.e. allowed purchased wallet)

To ensure that the royalties are paid, the validation script verifies that there are only two resulting UTXO of the "purchase" endpoint, the first UTXO contains x% of ADA to hardwritten address (i.e. royalty ) , the second UTXO is copy of the exact same script (for future selling)

Could that be done in the described way above ?
What is the exhaustive list of the parameters available for a smart validator to work?
Thank you in advance

Should one of the answers be marked as accepted?

Yes, it can be done. Just create a smart validator that makes sure, that when the UTXO containing the asset is spend to a new address, it also requires an additional input for the royalty address.
I believe you are correct in your second question.

sorry I just rewrote my question with more details ^^

You can wrap a native asset into a tailored smart contract, but I think this only makes sense if you also provide the platform to interact with these smart contracts. It is not a sell-and-forget transaction where the buyer can do whatever he wants including using DEXs to trade his asset.


text:
Blockfrost API and IPFS issues
Right now I have some NFTs to pin on the blockfrost IPFS. That way I don't need to run the node 24h a day. But for some reason the API returns an error when I try to add new assets.
I'm using a free account and have used 0/100mb so far. I used that before and it worked but now it doesn't anymore.
This is the endpoint I'm using:
curl "https://ipfs.blockfrost.io/api/v0/ipfs/add" \
  -X POST \
  -H "project_id: $PROJECT_ID" \
  -F "file=@./README.md"

The file I want to upload is a zip with a few KB, so not a big thing.
The error is an invalid project key, support says I need an IPFS key but I don't know how to obtain that.

Can you please share the error?

@MarekMahut-StakeNuts hi, this is basically a forbidden 403 error. I dont know why because I'm using my correct api. support says I must use a ipfs key but I dont know how to generate those...

Well, this is strange but blockfrost doesnt have the same api key for cardano mainnet and the ipfs.
You must create another project in order to use their api.
that's it.

Yes, that's correct - each network is a different API endpoint. Cardano maininet, Cardano testnet, IPFS, Cardano Alonzo...


text:
Deriving Show Compilation Error on Plutus Playground
I seem to be getting a compilation error when I try to compile any of the example files on my local host configuration for the Plutus Playground. The error is pictured here:
And basically it seems that no matter which example file I try and run I always end up getting a deriving show error. I am using an oracle VM and have installed the binaries for nix and have been running everything out of nix-shell.
Here is a better version of the error I've been receiving, this time on Week03's IsData.hs file, and I get the error at the 'Deriving Show' for MySillyRedeemer:
Then when I add the 'Show' to the Playground.Contract the error morphs into this:

So at this point I am really not sure what to do, all of these errors I encounter on my localhost server. I've reinstalled the plutus git and nix as well and I can't seem to figure out why I have these errors. And the errors do all seem to be 'not in scope' related so maybe its a a case of me not having certain files downloaded?
EDIT: Here is a copy of both the 'deriving show' error code:
error:
    Not in scope: type constructor or class ‘Show’
    Perhaps you want to add ‘Show’ to one of these import lists:
      ‘Prelude’ (/run/user/1000/web-ghc-work-f4d3c6b7d9d2297b/Main.hs:32:1-54)
      ‘Playground.Contract’ (/run/user/1000/web-ghc-work-f4d3c6b7d9d2297b/Main.hs:29:1-103)
   |
38 |     } deriving Show
   |                ^^^^

As well as one of the error code I get when I add 'Show' to the import list via Playground.Contract:
error:
    Not in scope: type constructor or class ‘Scripts.ScriptType’
    Module ‘Ledger.Typed.Scripts’ does not export ‘ScriptType’.
   |
59 | instance Scripts.ScriptType Vesting where
   |          ^^^^^^^^^^^^^^^^^^

+1 and welcome to the site, but it's typically better to copy and paste code and error messages into code blocks: This would help for blind people that are using screen readers, it would help with seachability, readability, reproducability, speed of loading on phones and on browsers with image blockers, etc.

Thank you @NikeDattani I've gone back and added code blocks to make it more understandable. Luckily I found the reddit post where somebody is hosting a public plutus playground that I can work on, found here (https://www.reddit.com/r/CardanoDevelopers/comments/mno89m/plutus_community_playground/). Its not ideal but it is a partial solution to my problem.

I believe your issue is stemming from the fact that the plutus team is updating the plutus library relatively quickly, and since the code written in the plutus-pioneer-program is now a month or two old, it is outdated and will only compile on the older version of the plutus playground.
I suggest you keep using the publicly hosted playground and then eventually move over to cabal and the terminal.

Yep, thats the plan for me going forward, it does the job but if I manage to find some workaround to it I'll post my solution, thanks!

You can run the Playground locally in Week 3 if you checkout the Plutus branch referenced in the Week03 cabal.project. See the tag option below.
source-repository-package
  type: git
  location: https://github.com/input-output-hk/plutus.git
  subdir:
    freer-extras
    playground-common
    plutus-core
    plutus-contract
    plutus-ledger
    plutus-ledger-api
    plutus-tx
    plutus-tx-plugin
    prettyprinter-configurable
    quickcheck-dynamic
  tag: 3aa86304e9bfc425667051a8a94db73fcdc38878

These are exactly the same errors that I get when I try to compile the Week 3 code with the latest Plutus master, so there is nothing wrong with your setup.
I was migrating the code to work with the master branch, but there have been a lot of Plutus changes since the Week 3 code was written which involved a lot of head scratching trying to figure out what was what.
As other posters have mentioned, checking out the correct commit should fix this for you.


text:
npm build of plutus client fails with "permission denied"
I am trying to run the Plutus playground using the Gitbook recipe (https://docs.plutus-community.com/docs/setup/WindowsWSL.html).
At step 15, the server starts fine, but trying to run the client with "npm run start" fails with the following
    [info] Copying from global cache: "tuples"
    [info] Copying from global cache: "web-html"
    [error] Installation failed
    [error] Error:
    [error] .spago/__download-catenable-lists-v5.0.1-1293619144260987/download: rename: permission denied (Permission denied)
    npm ERR! code ELIFECYCLE
    npm ERR! errno 1
    npm ERR! plutus-playground-client@1.0.0 purs:compile: `spago build`
    npm ERR! Exit status 1
    npm ERR!
    npm ERR! Failed at the plutus-playground-client@1.0.0 purs:compile script.

It seems that the npm script is trying to download something into a (read-only) nix store. How do I get the client to start?
I found some other issues (e.g. Installation failed on Ubuntu 20.04 in WSL on Windows 10 #689) reporting this error, but the reported fix is to close VSCode, so it is no longer accessing the build directories.  I am not currently using VSCode.  However, to make sure it was not some other lingering file contention, I restarted my PC and did nothing except the build on a newly restarted system.  Same error.

Have you tried deleting .spago directory? The npm or spago for purescript builds are not using nix store when you invoke them directly.

I deleted .spago.  Still fails, same error on a different file.  Per the cookbook instructions, I am running "npm run start" within a Nix shell, so all the files are within the nix store.  Your comment implies that I should not be using nix-shell? Is that what you meant?

No, you should be using nix-shell, it spawns a development shell for you with the required tools available but these have their own state directories. Also check if you have enough free space.

210 GB free on my C drive.

I found a resolution to the problem.
In sheer frustration, I spun up a Windows Hyper-Visor VM and started provisioning it from scratch with WSL2, Nix, etc, and nothing else.  After cloning the plutus repository, I got a strange git error (https://github.com/docker/for-win/issues/6284).  The resolution was to move the git repository from the windows-hosted file system (e.g. C:...) to the Ubuntu-hosted file system (\WSL$/mnt...).  Even though the systems are allegedly interoperable, apparently it is not perfect.
Re-cloning the plutus repository under my linux home directory caused the build problem to disappear.   (I had been downloading under my Windows-home directory when the error occured.)
Now I can do my Plutus Pioneer homework...

I just tried to run this using the latest Plutus commit and received the same errors. I tried deleting various generated files with no luck. However, when I re-cloned the entire Plutus repo and tried again, all was good once more, so there was something hanging around that needed to be deleted, but not sure what it was.
If you haven't already, could you try deleting and re-cloning and see if that helps?

I deleted, cloned, checked out the commit referenced in week01 cabal.build and reexecuted the recipe. I still get the same error - ".spago/__download-aff-v5.1.2-db16975bf2436f41/download: rename: permission denied (Permission denied)"


text:
How does `submitTxConstraintsWith` make usage of the ScriptLookups?
submitTxConstraintsWith :: ScriptLookups a -> TxConstraints (RedeemerType a) (DatumType a) -> Contract w s e Tx
How does submitTxConstraintsWith make usage of the ScriptLookups?
I always see it used like this: ledgerTx <- submitTxConstraints (swapInst oracle) tx
I am wondering why the ScriptLookups?

The family of submitTx functions all create transactions from the constraints submitted in the arguments. The most general implementation of the function is
submitTxConstraintsWith
  :: ScriptLookups a
  -> TxConstraints (RedeemerType a) (DatumType a)
  -> Contract w s e Tx

Here ScriptLookups a takes a lookup of the (Plutus compiled) scripts that are required by the transaction for on-chain execution.
This link gives an overview of the functions that are implemented. I added it as illustration as I don't know what Plutus commit it belongs to.

So, the transaction that ends up being submitted to the network will have as output/UTXO the script, right? instead of say a public key hash for example. ? @vcwebco

Not as output, but as constraint. In the case of a script the constraint is a validator that upon execution must return true for the transaction to succeed. The spending transactions that consume UTXOs from the smart contract need to supply validator script hash and (compiled) code. The producing transactions only need to supply the validator hash. It is explained  in the Plutus Pioneer Program - Iteration #2 - Lecture #2 video at minute 37.


text:
How expressive & secure is the Plutarch eDSL?
The Plutarch eDSL tries to control how plutus core is generated to create a smaller and thus a more efficient validator script (their GitHub).
I am not an in depth user of this tool. Does its approach reduce the expressiveness of the validator script? Moreover, does it reduce the intention of the script and thus lead to a loss of security?
This question is especially relevant due to recent MinSwap exploit (they use Plutarch).

I'm approaching the tool so I would not consider myself a Plutarch expert
however to my understanding, Plutarch is designed to be compatible with the entire PlutusTx API
since the real code of smart contracts (that goes on-chain) is Untyped  Plutus Core (UPLC) and both PlutusTx and Plutarch do fully cover UPLC Abstract Syntax Tree Plutarch should be equivalent in terms of expressiveness to PlutusTx.
regarding security what Plutarch does more than PlutusTx is just being strictly-evaluated so the underlying logic should not be different, only the way to get to the final result changes
MinSwap did used both PlutusTx and Plutarch for the smart contracts, and the incriminated code (validateMintNFT) was written using PlutusTx
in particular the function isUnity was allowing to duplicate (not so much) Non Fungible Tokens
tweag (the company that audited the smart-contracts prior releasing them) has an entire dedicated article


text:
How does the English Auction contract handle concurrency?
In the English Auction example, let's say both wallet 2 and 3 submit a transaction to bid at the same time.
(In the simulator, I just don't add a wait time between wallet 1&2 bids).
When Wallet 1 closes the auction, nothing happens in the simulator - only the first transaction is seen :

In general, how does Cardano handle a situation when 2 wallets (say from different geographical locations) submit transactions at the same time ? Do both transactions fail or just 1 ?

Whichever transaction the block producer decides to include in block will succeed. Only one can succeed though.
The auction datum exists on a UTxO and each UTxO can only be spent once. In the case of the auction, the validator requires a new UTxO with a new Datum is created to replace the spent TxO. That new Datum isn't visible until the next block though.
Concurrency is a popular topic of conversations in the community and there are many ways a dApp designer can allow participants to interact concurrently. It often requires architectures that are unique to Cardano. Check out this post which includes a lot of helpful resources about concurrency.

To add to the above, this is a simple example and doesn't have concurrency support in it. A more complex script would likely have some sort of concurrency model.


text:
Implementing CIP-008 (signData function) in Java
I'm trying to implement what's discussed in this topic: How to verify data signed with nami wallet in a node backend? but in Java.
Obviously I don't have the js/rust lib I can play with, so I have to implement/integrate all the bits myself.
While I've successfully implemented the code to use the Ed25519 standard, and in this repo there is the code and a few examples github I don't seem to be able to verify the data returned by the signData method of the wallet (that I assume uses the same standard).
Now it's my understading that the COSE object contains all that I need to at least verify the payload has been signed with the public key returned with COSE object itself. Looking at the sample in the post above, and using the https://cbor.me/ website, I guess that:

674D11E432450118D70EA78673D5E31D5CC1AEC63DE0FF6284784876544BE340 is the HEX of the signed message
68656C6C6F is the HEX of the message to sign
01D2EB831C6CAD4ABA700EB35F86966FBEFF19D077954430E32CE65E8DA79A3ABE84F4CE817FAD066ACC1435BE2FFC6BD7DCE2EC1CC6CCA6CB is the HEX of the Base Address of the wallet
A3B5ACD99DF5F3B5E4449C5A116078E9C0FCFC126A4D4E2F6A9565F40B0C77474CAFD89845E768FAE3F6EEC0DF4575FCFE7094672C8C02169D744B415C617609 is the HEX of the Public Key of the wallet.

Now, if I used the public key at (4) along with signed (1) and unsigned (2), and I test with the code (taht I know that works!) I wrong for the verification, it doesn't pass. So I guess one of the assumption i wrong.
I'm sure that (2) is the hex of the message to sign, so now either (1) is not the signed message or (4) is not the public key. Or they are in a different format
In java the code I'm running looks like the following
var msg = "hello".getBytes(StandardCharsets.UTF_8);
var publicKey = new Ed25519PublicKeyParameters(Hex.decode("A3B5ACD99DF5F3B5E4449C5A116078E9C0FCFC126A4D4E2F6A9565F40B0C77474CAFD89845E768FAE3F6EEC0DF4575FCFE7094672C8C02169D744B415C617609"), 0);
var verifier = new Ed25519Signer();
verifier.init(false, publicKey);
verifier.update(msg, 0, msg.length);
var outcome = verifier.verifySignature(Hex.decode("674D11E432450118D70EA78673D5E31D5CC1AEC63DE0FF6284784876544BE340"));
System.out.println("Outcome: " + outcome);

Any help would be greatly appreciated

After the CIP-0030 update you won't get the publicKey in the protected headers, but rather in the response object from signData directly, so the above answer won't work anymore.
Here is the example of the verification after the update: https://github.com/MartinOndejka/cip-0008-verification

First part of the solution can be found here:
https://github.com/bloxbean/cardano-client-examples/blob/cip008/src/main/java/com/bloxbean/cardano/client/examples/cip8/CIP8CBORParser.java
Code pasted here to keep track
package com.bloxbean.cardano.client.examples.cip8;

import co.nstant.in.cbor.CborDecoder;
import co.nstant.in.cbor.model.*;
import com.bloxbean.cardano.client.crypto.CryptoException;
import com.bloxbean.cardano.client.transaction.util.CborSerializationUtil;
import com.bloxbean.cardano.client.util.HexUtil;
import net.i2p.crypto.eddsa.EdDSAEngine;
import net.i2p.crypto.eddsa.spec.EdDSANamedCurveTable;
import net.i2p.crypto.eddsa.spec.EdDSAParameterSpec;
import net.i2p.crypto.eddsa.spec.EdDSAPublicKeySpec;

import java.security.MessageDigest;
import java.security.Signature;
import java.util.List;

public class CIP8CBORParser {
    private static final EdDSAParameterSpec spec = EdDSANamedCurveTable.getByName(EdDSANamedCurveTable.ED_25519);

    public void parse() throws Exception {
        //Payload = "hello"
        String coseSignMsgInHex = "845869a30127045820674d11e432450118d70ea78673d5e31d5cc1aec63de0ff6284784876544be3406761646472657373583901d2eb831c6cad4aba700eb35f86966fbeff19d077954430e32ce65e8da79a3abe84f4ce817fad066acc1435be2ffc6bd7dce2ec1cc6cca6cba166686173686564f44568656c6c6f5840a3b5acd99df5f3b5e4449c5a116078e9c0fcfc126a4d4e2f6a9565f40b0c77474cafd89845e768fae3f6eec0df4575fcfe7094672c8c02169d744b415c617609";

        //CBOR parsing starts here ###################
        List<DataItem> dataItemList  = CborDecoder.decode(HexUtil.decodeHexString(coseSignMsgInHex));

        List<DataItem> topArray = ((Array) dataItemList.get(0)).getDataItems();
        ByteString protectedHeaderBs = (ByteString) topArray.get(0);
        Map unprotectedMap = (Map) topArray.get(1);
        ByteString messageToSignBS = (ByteString) topArray.get(2);
        ByteString signatureArrayBS = (ByteString) topArray.get(3);

        byte[] message = messageToSignBS.getBytes();
        byte[] signature = signatureArrayBS.getBytes();

        System.out.println(new String(message));

        //parse protected header map bytestring
        List<DataItem> protectedHeaderMapDIList = CborDecoder.decode(protectedHeaderBs.getBytes());
        Map protectedHeaderMap = (Map) protectedHeaderMapDIList.get(0);

        ByteString publicKeyBS = (ByteString) protectedHeaderMap.get(new UnsignedInteger(4));
        byte[] publicKeyBytes = publicKeyBS.getBytes();

        ByteString addressBS = (ByteString)protectedHeaderMap.get(new UnicodeString("address"));
        System.out.println("Address >> " + HexUtil.encodeHexString(addressBS.getBytes()));
        //CBOR parsing ends her ###################

        //Create SignatureStructure. This is passed as message during signature verification
        Array sigStructArray = new Array();
        sigStructArray.add(new UnicodeString("Signature1"));
        sigStructArray.add(protectedHeaderBs);
        sigStructArray.add(new ByteString(new byte[0]));
        sigStructArray.add(messageToSignBS);

        byte[] messageToVerify = CborSerializationUtil.serialize(sigStructArray); //serialize
        //End SignatureStructure

        boolean verified = verify(messageToVerify, signature, publicKeyBytes);
        System.out.println("Verification status >> " + verified);
    }

    public boolean verify(byte[] message, byte[] signatureBytes, byte[] publicKeyBytes) {

        try{
            net.i2p.crypto.eddsa.EdDSAPublicKey publicKey = new net.i2p.crypto.eddsa.EdDSAPublicKey(new EdDSAPublicKeySpec(publicKeyBytes, spec));
            Signature signature = new EdDSAEngine(MessageDigest.getInstance(spec.getHashAlgorithm()));
            signature.initVerify(publicKey);
            signature.setParameter(EdDSAEngine.ONE_SHOT_MODE);
            signature.update(message);
            return signature.verify(signatureBytes);
        }catch(Exception e){
            throw new CryptoException("Extended signing error", e);
        }
    }

    public static void main(String[] args) throws Exception {
        new CIP8CBORParser().parse();
    }
}

Kudos to @Satya
Second part missing is the adderss verificaiton/validation.
Will add as soon as it's done.


text:
Verifying user data sent to a smart contract
so i've got a fun idea to use an in game puzzle and the infinite solutions possible as a method to mine a coin. Essentially i want the gamer to create a system, and however long it runs for without falling apart will dictate how much currency is minted to reward the system. (kinda like earning in-game points, except i want it too be a crypto-token)
the slight catch is i'd like it too be a mobile game written in Unity, so i don't think i can verify the solution 'on-chain', but i also don't want someone to be able to just call a smart contract with "?duration=allTheTime" to mint all the monies fraudulently.
How would everyone else approach this? I've considered maybe a system of 'authorized accounts' that can do verification of submitted solutions, or somehow crowd sourcing the verification in a decentralized manner, but that stuff gets complicated fast. thoughts?
Edit: no idea why this question is being downvoted. I'd like to give a simpler example. giving out points in a game, and recording those on the blockchain.. "you chopped some wood, 2 points"... how to prevent fraud when the smart contract is publicly exposed to mint new points. store the private minting key IN-APP? (obviously not). help.


text:
How to create a smart contract constant variable?
I am using state machines to create a smart contract. How can I create a variable that will be defined by the user when it runs the first step of the state machine and that then can't be modified anymore?
In other words, it's a variable that is created by using the smart contract endpoints but that can't be modified later on until the state machine reaches its end.
Finally, would it be possible to make this validation on-chain?

You could modify your datum type to something like so: {constants: {...}, old_datum: {...}}
Then, make your old validations take old_datum (you could unwrap old_datum as the same name as your current datum even), and validate output constants==input constants. You will want an exception to this rule if the input does not come from the script, to allow setting the constants at first, so you could logically enforce something like "for each input utxo, if that input resided at this script, enforce that there is some unique output utxo with the same constants".

Accidentally made a new answer when I meant to update old one.


text:
What is the Nakamoto Coefficient of Cardano?
Balaji introduced the Nakamoto Coefficient several years ago:

The basic idea is to (a) enumerate the essential subsystems of a decentralized system, (b) determine how many entities one would need to be compromised to control each subsystem, and (c) then use the minimum of these as a measure of the effective decentralization of the system. The higher the value of this minimum Nakamoto coefficient, the more decentralized the system is.

He also tried to perform an initial analysis of the coefficient for:
bitcoin:

and ethereum:

What's the Nakamoto Coefficient for Cardano? Charles regularly claims Cardano is (among) the most decentralized cryptocurrencies in the world - has anyone tried to quantify that?

this graphs show the nakamoto coefficient and mav factor epoch by epoch
https://datastudio.google.com/u/0/reporting/3136c55b-635e-4f46-8e4b-b8ab54f2d460/page/p_9vyfu6gorc

Wow that's amazing. If I'm reading this correctly (which I might not be since it's new to me) the graph represents the Nakamoto coefficient when looking just at stake pools. As I understand the concept of the coefficient, it should look at the ecosystem as a whole. For example, there might be many stake pools but they all run the same software and maybe that software is highly centralized in some way. Do you know if there's a more holistic measure of the Nakamoto Coefficient for the ADA ecosystem?

You are correct, see the interesting CIP-50 define k-effective.
https://github.com/michael-liesenfelt/CIPs/blob/CIP-Liesenfelt-Shelleys_Voltaire_decentralization_update/CIP-Liesenfelt-Shelleys_Voltaire_decentralization_update/README.md


text:
Mathematical equivalence of Account and eUTxO model
I've heard that the eUTxO model and the Account model are mathematically equivalent in terms of expressiveness in various YouTube videos. I've also heard that the eUTxO model is a strict superset of the Account model (ie: the eUTxO model can do everything the Account model can do, and more). Are these ideas/facts true? I've been trying to find a high quality source for this idea/fact but haven't been able to find one.
I tried reading the paper presenting the eUTxO model but my lack of formal math training made it a bit difficult and I didn't find any mentions of Account model equivalence.
Does anyone know of high quality sources which confirm or reject out these ideas?

The reason eUTXO is considered a superset of the account model is because it is possible to create constraint emitting machines (CEMs) on the eUTXO model, as mentioned in the paper you linked. To summarize:
Since "smart contract" logic is encapsulated entirely within individual UTXO(s), it is possible to perfectly capture logic of arbitrary complexity by aggregating and quarantining UTXOs into a sort of "black box" on-chain.
It is this CEM principle that forms the basis of the Hydra Head Protocol; allowing the creation of mini-ledgers that can be configured to behave in an account-style fashion, all while periodically committing snapshots to the overarching UTXO-style main-chain.
All of this is to say, that any and all UTXO logic can be expressed in an accounts-like fashion, but the reverse is not true. Therefore, the UTXO model is, expressively speaking, a superset of the account model.

Thank you for the amazing answer! I know this is a big ask but do you mind elaborating? I don't have intuition for what the following means: perfectly capture logic of arbitrary complexity by aggregating and quarantining UTXOs into a sort of "black box" on-chain. Also, is there any chance you can elaborate on why the reverse isn't true? Is there a simple example of a UTXO smart contract that cannot be expressed in an account-like way?

UTXOs are like little boxes that contain data (and logic) with zero external dependencies. If we aggregate a bunch of these little boxes into a bigger box (lets call the bigger box a "Head"), we can rigorously guarantee that this new Head is not logically dependent on anything outside of the UTXOs that went into its construction.
However, we cannot make the same zero-external-dependency guarantees for an accounts-based ledger, because it is already, by its nature, one big box/state of constantly changing interdependencies (almost like one big head).

I stumbled across this paper by IOHK which seems to show this sort of equivalence.
I'm going to try to read it and see what I can learn. I suspect this might be the best resource for learning about this mathematical equivalence between those two models.
EDIT: this seems like the paragraph from the paper above which confirms the idea that eUTxO is a mathematical superset of the account model:

Despite the accounting equivalence implied by the
translations, Proposition 2 and the translation of Sec.
5.2 show that it is generally necessary to create several
account-based transactions to simulate the effect of
a single UTXO-based transaction. This is important:
while all the value transfers in a single UTXO-based
transaction are processed atomically and simultaneously, the corresponding account-based transactions
are not guaranteed to be so. Theoretically, there may
be a wide time gap between their executions.


text:
Contract continuity in the eUTxO model
The paper which introduces the eUTxO model mentions an idea called contract continuity:

we need to be able to enforce that
the same contract code is used along the entire sequence of transactions — we
call this contract continuity

and that continuity is achieved by passing the entire transaction to the validator:

Thus a validator can inspect the transaction
that attempts to spend its output and, in particular, it can ensure that the
contract output of that transaction uses validator code belonging to the same
contract — often, this will be the same validator

Based on my current understanding, it's intuitive to me that if a transaction consumes outputs from a single contract, the validator of those outputs can enforce that the new outputs of the transaction use the same validator.
What I'm having trouble understanding is what happens when a single transaction consumes two UTxOs with different contracts. Suppose there are two UTxOs a and b and that UTxO a is validated by scriptA while UTxO b is validated by scriptB. If a single transaction tx consumes both a and b, how is contract continuity preserved?
EDIT: I realize the second item I quoted above isn't quite clear to me and another question popped into my mind, how does validator code relate to the notion of contract and contract output?


text:
Resources to learn about block pipelining?
Are there resources to learn about block pipelining in Cardano as mentioned in this video?

There is a pipelining introduction blog post at
https://iohk.io/en/blog/posts/2022/02/01/introducing-pipelining-cardanos-consensus-layer-scaling-solution/


text:
Plutus Pioneer lecture 3 homework 1 vesting logic
I'm having some trouble figuring out the vesting logic in homework 1 of the Plutus pioneer program lecture. I eventually gave up and looked at the solution which seems to be exhibiting the same "bug" (I put bug in quotes because clearly I'm misunderstanding something).
As I understand the logic of the transaction construction, the giver (or beneficiary2) can claim the gift anytime after the deadline while the recipient (or beneficiary1) can claim the gift anytime before the deadline (inclusive). Is that correct?
If so, I'm having trouble understanding why the following simulation seems to succeed. I'll provide screenshots and then go through my understanding of it. Here are the values entered for the simulation that seems buggy to me:

and here the final state of the blockchain:

In this simulation, Wallet 1 is giving 10 ADA to 39f713d0a644253f04529421b9f51b9b08979d08295959c4f3990ee617f5139f which is the hash of Wallet 2 (this can be confirmed by looking at the hash of the wallets in the final state screenshot). This gift has a deadline of 1596059101000 which is slot 10 based on:
Prelude Ledger Wallet.Emulator Data.Default Ledger.TimeSlot Week03.Homework2> posixTimeToEnclosingSlot def 1596059101000
Slot {getSlot = 10}

and
Prelude Ledger Wallet.Emulator Data.Default Ledger.TimeSlot Week03.Homework2> slotToBeginPOSIXTime de
f 10
POSIXTime {getPOSIXTime = 1596059101000}

Curiously, it seems that Wallet 2 can grab the gift at slot 11 which is after the deadline. It's very possible that my understanding of the transaction logic is incorrect. To double check, I also ran the same code with the following simulation (the only difference is that the second step of the simulation waits until slot 5 instead of slot 11) and it also succeeded which confuses me even more. I expect that one of these simulations should fail but can't figure out why.

Is there a bug with the solution for homework 1 in lecture 3? Am I misunderstanding something about the logic of the solution?
EDIT: here's another interesting point, with the suggested solution I can't seem to get Wallet 1 to grab the gift it provides. I've tried waiting for 1 block after the gift, waiting until slot 5 and waiting until slot 15 before attempting for Wallet 1 to grab it's gift and in all cases it fails - the "grab" transaction never reaches the blockchain and seems to fail client side with found 0 gift(s) to grab.

On first glance, I don't see any flaws in your logic. Could be a bug in the Playground? I don't have time rn to dig in further. I'll try to come back to it.

ah yeah, could be a bug in the playground. I'm running the playground on commit ea0ca4e9f9821a9dbfc5255fa0f42b6f2b3887c4 but now I'm realizing that the required plutus commit changes from week to week. ea0ca4e9f9821a9dbfc5255fa0f42b6f2b3887c4 is from week 1 while week 3 requires 219992289c6615e197069d022735cb4059d43229.

Changing the commit of the local plutus repo to 219992289c6615e197069d022735cb4059d43229 doesn't fix this unfortunately

It was a long shot. I don't use the Playground at all, I just use the Emulator Trace: https://github.com/input-output-hk/plutus-pioneer-program/blob/9c83322743e393427acdc24525b04dfc1c49084d/code/week05/src/Week05/NFT.hs#L87 It might be easier to debug your code using that (but that's jumping ahead in the progam).

Oops, checking out commit 219992289c6615e197069d022735cb4059d43229 does solve the problem, I must have fat fingered something in the earlier comment which said it doesn't. Commit ea0ca4e9f9821a9dbfc5255fa0f42b6f2b3887c4 seems to have a broken notion of time: https://cardano.stackexchange.com/questions/3997/plutus-playground-server-sense-of-time-is-incorrect/3998#3998

Haha. Good to hear.

Turns out I wasn't using the correct checkout of plutus. More details can be found at the following Cardano StackExchange answer: plutus-playground-server sense of time is incorrect


text:
Error when building HSL for GHC 8.10.4.20210212
I'm trying to get the haskell language server installed on my mac and I"m following the docs at https://docs.plutus-community.com/docs/setup/editors/prerequisites.html but they seem to not work. My GHC version (in a nix shell) is:
11:31AM /Users/paymahn/haskell-language-server nix  ✘ 1 master ✱
 ❯❯❯ ghc --version
The Glorious Glasgow Haskell Compilation System, version 8.10.4.20210212

and when I invoke ./cabal-hls-install hls-8.10.4.20210212 I get the following output:
Error when running Shake build system:
  at want, called at src/Development/Shake/Internal/Args.hs:83:67 in shk-0.19.6-79b14aaa:Development.Shake.Internal.Args
* Depends on: hls-8.10.4.20210212
  at error, called at src/Development/Shake/Internal/Rules/File.hs:179:58 in shk-0.19.6-79b14aaa:Development.Shake.Internal.Rules.File
* Raised the exception:
Error, file does not exist and no rule available:
  hls-8.10.4.20210212

Anyone know what this means and how to fix it?
EDIT: I get the same error if I invoke stack ./install.hs 8.10.4.20210212

Looks like the stack.yaml for 8.10.4 was removed which is why this error happens. Checking out tag 1.4.0 fixes it.


text:
Logging in validator
I'm working through the Plutus Pioneer program and I have a bug in my implementation of the validator for homework one. I'd like to add some logging to the validator to get more insight into what I'm doing wrong.
I've seen that the logInfo function is used in the wallet code and I've tried adding that to the validator like:
mkValidator dat _ ctx = do
    logInfo @P.String $ printf "deadline %s" (P.show $ deadline dat)
    False -- dummy value to figure out how to get logging to work

but when I do that I get the following error:
• Couldn't match expected type ‘Bool’
              with actual type ‘Contract w0 s0 e0 b0’
• In a stmt of a 'do' block:
    logInfo @P.String $ printf "deadline %s" (P.show $ deadline dat)
  In the expression:
    do logInfo @P.String $ printf "deadline %s" (P.show $ deadline dat)
       False
  In an equation for ‘mkValidator’:
      mkValidator dat _ ctx
        = do logInfo @P.String
               $ printf "deadline %s" (P.show $ deadline dat)
             False

Upon checking the type of logInfo I see that it has the type logInfo :: forall a w (s :: Row *) e. ToJSON a => a -> Contract w s e () which seems to match up with the error that's given.
How come I can't use this logging function if I'm later returning False? I suspect I'm misunderstanding something fairly basic about how haskell works.

I'll use this answer to log my journey as I try things out.
Tentative Solution/Answer
Looks like P.show can't be used in a validator based on https://discord.com/channels/826816523368005654/826829805387120690/892870961353879592
I'll wait for more confirmation before accepting this. I hope that's not the case.
Attempt 1
I've also tried using trace with
mkValidator dat _ ctx = do
    trace $ printf "deadline %s" (P.show $ deadline dat)
    False
but that also results in an error:

• Couldn't match expected type ‘Bool’ with actual type ‘a0 -> b0’
• In a stmt of a 'do' block:
    trace $ printf "deadline %s" (P.show $ deadline dat)
  In the expression:
    do trace $ printf "deadline %s" (P.show $ deadline dat)
       False
  In an equation for ‘mkValidator’:
      mkValidator dat _ ctx
        = do trace $ printf "deadline %s" (P.show $ deadline dat)
             False

Attempt 2
Looks like using do in a validator is a fools errand. Now I'm trying to add debug info to the trace message.
mkValidator :: VestingDatum -> () -> ScriptContext -> Bool
mkValidator dat _ ctx  = traceIfFalse (P.show $ deadline dat) False

but it turns out that P.show doesn't return the correct type (it returns [P.Char] when a BuiltinString is required). Trying to coerce [P.Char] to a BuiltinString using stringToBuiltinString from https://playground.plutus.iohkdev.io/doc/haddock/plutus-tx/html/PlutusTx-Builtins-Class.html#v:stringToBuiltinString results in a very large error that looks like linker problems:

GHC Core to PLC plugin: E043:Error: Reference to a name which is not a local, a builtin, or an external INLINABLE function: Variable GHC.CString.unpackAppendCString# No unfolding Context: Compiling expr: GHC.CString.unpackAppendCString# Context: Compiling expr: GHC.CString.unpackAppendCString# Plutus.V1.Ledger.Time.$fShowPOSIXTime4 Context: Compiling expr: GHC.CString.unpackAppendCString# Plutus.V1.Ledger.Time.$fShowPOSIXTime4 (GHC.CString.unpackAppendCString# Plutus.V1.Ledger.Time.$fShowPOSIXTime3 (case GHC.Show.$w$cshowsPrec4 0# (x `cast` (Plutus.V1.Ledger.Time.N:POSIXTime[0] :: GHC.Types.Coercible Plutus.V1.Ledger.Time.POSIXTime GHC.Integer.Type.Integer)) Plutus.V1.Ledger.Time.$fShowPOSIXTime5 of { (# ww3 [Occ=Once], ww4 [Occ=Once] #) -> GHC.Types.: @ GHC.Types.Char ww3 ww4 })) Context: Compiling expr: \ (x [Occ=Once] :: Plutus.V1.Ledger.Time.POSIXTime) -> GHC.CString.unpackAppendCString# Plutus.V1.Ledger.Time.$fShowPOSIXTime4 (GHC.CString.unpackAppendCString# Plutus.V1.Ledger.Time.$fShowPOSIXTime3 (case GHC.Show.$w$cshowsPrec4 0# (x `cast` (Plutus.V1.Ledger.Time.N:POSIXTime[0] :: GHC.Types.Coercible Plutus.V1.Ledger.Time.POSIXTime GHC.Integer.Type.Integer)) Plutus.V1.Ledger.Time.$fShowPOSIXTime5 of { (# ww3 [Occ=Once], ww4 [Occ=Once] #) -> GHC.Types.: @ GHC.Types.Char ww3 ww4 })) Context: Compiling definition of: Plutus.V1.Ledger.Time.$fShowPOSIXTime_$cshow Context: Compiling expr: Plutus.V1.Ledger.Time.$fShowPOSIXTime_$cshow Context: Compiling expr: Plutus.V1.Ledger.Time.$fShowPOSIXTime_$cshow (case dat of { Main.VestingDatum _ [Occ=Dead] _ [Occ=Dead] ds_dLa0 [Occ=Once] -> ds_dLa0 }) Context: Compiling expr:

P.show will always fail inside a validator, because you can't use functions defined in Haskell Prelude, you need to use instead PlutusTx.Prelude

Does PlutusTx.Prelude include a show function? I couldn't find one but maybe I wasn't looking in the right place.

There isn't, since show transforms anything into a String and PlutusTx.Prelude only works with BuiltinString or BuiltinByteString

Same here. Get this error every time I there is a variable in the validator.

You're running into trouble because logInfo is meant to be used inside the Contract monad. The Wallet code uses the Contract monad but the validator code doesn't.
If you're not familiar with how monads and do blocks work, I'd check out Lecture #4
As for logging inside of validators, I'd look at using trace, traceIfTrue, or traceIfFalse. I've only used traceIfFalse though. Remember, validators are compiled into Plutus and run on the chain, so they aren't going to log like normal code. Whereas the wallet code is run natively on your machine.
Hope that helps.

Is it possible to use that combined with an arbitrary variable? For example, if I want to dynamically display the number of tokens that are missing for the script to validate.

Thanks for the great answer! I stumbled on that myself but it's good to know what I found myself is accurate. @Mateus I don't think you can log arbitrary variables within trace or it's derivatives because the Plutus Prelude doesn't offer a show function.

Validators are compiled into Plutus Core language which is human-unreadable. It's not possible to compile something that will be only available at run-time because it's literally not there to be compiled. You can log variables that are available at compiler.

GHC Core to PLC plugin: E043:Error: Reference to a name which is not a local, a builtin, or an external INLINABLE function

This error means that you are trying to compile something that will be available at run-time.


text:
Cardano-cli error: "Invalid argument `"type":'"
I'm new and I'm following cardano developers tutorial to create NFT. I arrived at some modified code for what I wanted to do. But get this "Invalid argument `"type":'" error. When building the transaction for minting. The other part of the transaction that is not the minting parts seems to work because I can make ordinary transaction and I'm using the testnet, running a testnet node with zsh. Cardano-cli version 1.33. Macbook pro M1 pro, macOS 12.2.1.
Here is the code:
cardano-cli query protocol-parameters \
--testnet-magic 1097911063 \
--out-file $HOME/nft/protocol.json

tokenname="5465737469616e"
tokenamount=1
txhash="989b03feb8885db90c6ca44065fe950a2208ba60c6d1b1f17aef87dcfd13c03b"
txix=0
policyid=$(cat $HOME/nft/policy/policyID)
script=$(cat $HOME/nft/policy/policy.json)
addressOut=$(cat $HOME/cardanotestwallet/keys/payment1.addr)
addressIn=$(cat $HOME/receive-ada-sample/keys/payment.addr)

fee=$(cardano-cli transaction build-raw \
--alonzo-era \
--tx-in ${txhash}#${txix} \
--tx-out ${addressOut}+0+"${tokenamount} ${policyid}.${tokenname}" \
--tx-out ${addressIn}+0 \
--mint="${tokenamount} ${policyid}.${tokenname}" \
--minting-script-file ${script} \
--invalid-hereafter ${slotnumber} \
--fee 0 \
--metadata-json-file $HOME/nft/metadata.json \
--out-file $HOME/nft/matx.raw

cardano-cli transaction calculate-min-fee \
--tx-body-file $HOME/nft/matx.raw \
--tx-in-count 1 \
--tx-out-count 2 \
--witness-count 1 \
--testnet-magic 1097911063 \
--protocol-params-file $HOME/nft/protocol.json)

fee=${fee%" Lovelace"}

funds=99829967
output=1700000
slotnumber=53264773
change=$((${funds}-${output}-${fee}))

cardano-cli transaction build-raw \
--alonzo-era \
--tx-in ${txhash}#${txix} \
--tx-out ${addressOut}+${output}+"${tokenamount} ${policyid}.${tokenname}" \
--tx-out ${addressIn}+${change} \
--mint="${tokenamount} ${policyid}.${tokenname}" \
--minting-script-file ${script} \
--invalid-hereafter ${slotnumber} \
--fee ${fee} \
--metadata-json-file $HOME/nft/metadata.json \
--out-file $HOME/nft/matx.raw

...And here is the full error code:
Invalid argument `"type":'

Usage: cardano-cli transaction build-raw
            [ --byron-era
            | --shelley-era
            | --allegra-era
            | --mary-era
            | --alonzo-era
            ]
            [--script-valid | --script-invalid]
            (--tx-in TX-IN
              [--tx-in-script-file FILE
                [(--tx-in-datum-file FILE | --tx-in-datum-value JSON VALUE)
                  ( --tx-in-redeemer-file FILE
                  | --tx-in-redeemer-value JSON VALUE
                  )
                  --tx-in-execution-units (INT, INT)]])
            [--tx-in-collateral TX-IN]
            [--required-signer FILE | --required-signer-hash HASH]
            [--tx-out ADDRESS VALUE
              [ --tx-out-datum-hash HASH
              | --tx-out-datum-hash-file FILE
              | --tx-out-datum-hash-value JSON VALUE
              | --tx-out-datum-embed-file FILE
              | --tx-out-datum-embed-value JSON VALUE
              ]]
            [--mint VALUE
              (--mint-script-file FILE
                [(--mint-redeemer-file FILE | --mint-redeemer-value JSON VALUE)
                  --mint-execution-units (INT, INT)])]
            [--invalid-before SLOT]
            [--invalid-hereafter SLOT]
            [--fee LOVELACE]
            [--certificate-file CERTIFICATEFILE
              [--certificate-script-file FILE
                [
                  ( --certificate-redeemer-file FILE
                  | --certificate-redeemer-value JSON VALUE
                  )
                  --certificate-execution-units (INT, INT)]]]
            [--withdrawal WITHDRAWAL
              [--withdrawal-script-file FILE
                [
                  ( --withdrawal-redeemer-file FILE
                  | --withdrawal-redeemer-value JSON VALUE
                  )
                  --withdrawal-execution-units (INT, INT)]]]
            [--json-metadata-no-schema | --json-metadata-detailed-schema]
            [--auxiliary-script-file FILE]
            [--metadata-json-file FILE | --metadata-cbor-file FILE]
            [--genesis FILE | --protocol-params-file FILE]
            [--update-proposal-file FILE]
            --out-file FILE

  Build a transaction (low-level, inconvenient)

  Please note the order of some cmd options is crucial. If used incorrectly may produce undesired tx body. See nested [] notation above for details.
Command failed: transaction calculate-min-fee  Error: /Users/myyenongianggiang/nft/matx.raw: /Users/myyenongianggiang/nft/matx.raw: openBinaryFile: does not exist (No such file or directory)
createN.sh: line 38: 99829967-1700000-: syntax error: operand expected (error token is "-")

Am I missing something really easy? can't find out what the problem is, would be very happy for getting some help. Been stuck...
Thank you very much in advance.
//Koki

The error states a missing file: matx.raw
I sugguest separating the build-raw and calc fee commands.
Edit: $slotnumber was not set before use in the first 'build-raw' statement.
Edit: Try the steps below manually one by one to confirm that things are as we expect before carrying on. Set the slotnumber to the appropriate value.
Edit: --minting-script-file expects a file path not data
Edit: User recreated the policy ID and the policy script - now working ok.
#Step 0 - Remove $HOME/nft/matx.raw if it exists
rm $HOME/nft/matx.raw

#Step 1
cardano-cli query protocol-parameters \
--testnet-magic 1097911063 \
--out-file $HOME/nft/protocol.json

#Step 2
tokenname="5465737469616e"
tokenamount=1
txhash="989b03feb8885db90c6ca44065fe950a2208ba60c6d1b1f17aef87dcfd13c03b"
txix=0
policyid=$(cat $HOME/nft/policy/policyID)
#script=$(cat $HOME/nft/policy/policy.json)
script="$HOME/nft/policy/policy.json"
addressOut=$(cat $HOME/cardanotestwallet/keys/payment1.addr)
addressIn=$(cat $HOME/receive-ada-sample/keys/payment.addr)

slotnumber=53264773

#Step 3 - Check each is set correctly
echo "This is step 3"
echo "A $txhash "
echo "B $txix"
echo "C $addressOut"
echo "D $tokenamount"
echo "E $policyid"
echo "F $tokenname"
echo "G $addressIn"
echo "H $script"
echo "I $slotnumber"

echo "About to run the first build-raw command"

cardano-cli transaction build-raw \
--alonzo-era \
--tx-in ${txhash}#${txix} \
--tx-out ${addressOut}+0+"${tokenamount} ${policyid}.${tokenname}" \
--tx-out ${addressIn}+0 \
--mint="${tokenamount} ${policyid}.${tokenname}" \
--minting-script-file ${script} \
--invalid-hereafter ${slotnumber} \
--fee 0 \
--metadata-json-file $HOME/nft/metadata.json \
--out-file $HOME/nft/matx.raw

echo "After the first build-raw"

Also, keep in mind that each command should be on one line, or use the line continuation character \ if split over multiple lines.

Thank you for your quick response. I tried your suggestion as mentioned and got the exact same error. And yes everything is on same line or "" is used when multiple lines. The "" don't seems to show when posting here. However they are there .

Thanks for the update.
I just noticed that slotnumber does not appear to be set before the first 'build-raw' attempt.
--invalid-hereafter ${slotnumber}
Can you set it at the top before running 'cardano-cli transaction build-raw...' eg  slotnumber=53264773

Okey. Tried moving the slotnumber higher above the first build-raw attempt, but still exact same error code.

slotnumber needs to be set before you use it eg BEFORE the line beginning:
fee=$(cardano-cli transaction build-raw...... Set it at the TOP right after the line: addressIn=$(cat....

Builds-raw and calc fee commands are now separated as suggested and slot number is set before first build-raw command (right after/under addressIn). Same error code created.

Can you try these steps in my updated answer.

Can you link in the document guide that you are following.

About to run the first build-raw
Command failed: transaction build-raw  Error: {
"type": "all",
"scripts":
[
{
"type": "before",
"slot": 53612937
},
{
"type": "sig",
"keyHash": "13589c57f20c76a46b508cca1f4434d0a1e3f568c3f359c02d2a8327"
}
]
}: {
"type": "all",
"scripts":
[
{
"type": "before",
"slot": 53612937
},
{
"type": "sig",
"keyHash": "13589c57f20c76a46b508cca1f4434d0a1e3f568c3f359c02d2a8327"
}
]
}: openBinaryFile: does not exist (No such file or directory)
After the first build-raw

Seems something wrong with my policy script?
I follow these guides:

https://developers.cardano.org/docs/native-tokens/minting-nfts#crafting-the-transaction
https://developers.cardano.org/docs/native-tokens/minting
https://devslug.com/how-to-mint-an-nft-on-cardano-testnet-using-the-command-line

Error at step #3. See above comment.

Ok good, that's moving along. One thing I noticed is that '--minting-script-file' accepts a file path. In your case it should be: '--minting-script-file $HOME/nft/policy/policy.json'

When I change from variable to path as suggested, I get this error instead:
About to run the first build-raw command
Command failed: transaction build-raw  Error: The "--mint" flag specifies an asset with a policy Id, but no corresponding monetary policy script has been provided as a witness (via the "--minting-script-file" flag). The policy Id in question is: 3d700373099c2b932990d812c02909223bc6587f2ef25b587e8d03e7
After the first build-raw

Ok good, that has progressed to the next issue. It looks like the policy.json and/or policyID need checking. Back up a few steps and look closely at how these are created and if there is something missing or incorrect.

Yes you are right! I recreated the policy ID and the policy script and together with the filepath change earlier it now works. Thanks a lot man!

That's great, glad to help


text:
version `GLIBC_2.33' not found
trying to install nix (on a clean fedora 35 server), getting this error, help!
/nix/store/sbbifs2ykc05inws26203h0xwcadnf0l-glibc-2.32-46/lib/libc.so.6: version `GLIBC_2.33' not found (required by /usr/local/lib/libsodium.so.23)

for me it worked to remove LD_LIBRARY_PATH from env

Try unsetting your LD_LIBRARY_PATH, like this:
unset LD_LIBRARY_PATH

Then restart your installation.
If you need more information, please check this GitHub Issue.


text:
Error - Building Cardano Node 1.35.4 in Ubuntu Linux 22.04
When building cardano-node-1.35.4 using
git checkout tags/1.35.4
cabal update
cabal build all

I get the following error
cabal: Failed to build tx-generator-2.2 (which is required by

test:tx-generator-test from tx-generator-2.2 and exe:tx-generator from

tx-generator-2.2).

Upon scrolling up a few lines, I see this
src/Cardano/Benchmarking/Script/Setters.hs:40:1: error:

    • Illegal constraint: c NumberOfInputsPerTx

        (Use ConstraintKinds to permit this)

    • In the instance declaration for

        ‘Data.Constraint.Extras.Has c_a3mLE Tag’

   |

40 | deriveArgDict ''Tag

   | ^^^^^^^^^^^^^^^^^^^

Can someone please help me understand what this error means and on how to solve this? Thanks in advance.

I think between CHaP movements and upstream updates the build process has started failing for 1.35.4, they've been fixed since on master branch. But for visibility of those using 1.35.4 to build:

Failed to build tx-generator-2.2 => This error itself would not prevent you to build cardano-node and cardano-cli binaries.
For those who receive an error with openssl, they'd need to modify cabal.project file as per this issue.
cabal install (running as-is for any component) was broken on that tag, fixed later on master

Thank you for your response. I will try this out. Yes, it wouldn’t prevent us from building binaries but the nodes won’t sync up to preview/prepped after that. That is the major issue am facing.

Sync of node should work fine on preview/preprod once node binary is built, and is actually used for node startup (you can confirm running node version via logs as well if using ScJson)

Hi @RdLrt, Sadly adjusting the cabal.project file did not work. However, I didn't receive any error on the master branch.

You should not use master branch, it may often contain changes that may not be supported by current network[s] or tools

What version of ghc are you using? Currently the only supported version is ghc-8.10.*.
Work is being done to support ghc-9.2.* and when that is supported across the complete stake, then support for ghc-9.10.* will be dropped.

Hi there, Thank you for your response. I am using the 8.10.7.


text:
Installing nix: where is shell profile - MacOS using zsh?
I am trying to install nix on my local iMac. I am following the following Guide to do that.  After executing
sh <(curl -L https://nixos.org/nix/install) --darwin-use-unencrypted-nix-store-volume

I get "Installing finished!" and I am requested to add the line:
. /Users/joeblogs/.nix-profile/etc/profile.d/nix.sh

"to your shell profile (e.g. ~/.profile)."
I am using a Mac (with zsh) and so what file is this shell profile referring to? For instance, i do not have a ~/.profile.

You'd have an easier time installing on a Linux machine. Try Linux mint.

So the following worked. Go to the following file:
/etc/zprofile

and add the following line:
. /Users/thanhdanhphan/.nix-profile/etc/profile.d/nix.sh

Close all your terminals and re-open a new one, try:
nix --version

and it should give you the latest nix version e.g (at the time of writing):
nix (Nix) 2.3.14

I had the same problem.  Try creating a file named .bash_profile in your user directory (/Users/joblogs/.bash_profile) and add the given line as it is written.  Restart the terminal and give it a go.

this does't work, maybe because i am using zsh


text:
How does the Fμω lambda calculus use C?
While poking around in the repositories I wondered how the sha2_256 algorithm was implemented in the PlutusTx module. I followed all the imports and got the following path

The sha2_256 function in PlutusTx.Builtins is defined at (1). In this module it is imported from a internal module with import name BI.

{-# INLINABLE sha2_256 #-}
-- | The SHA2-256 hash of a 'ByteString'
sha2_256 :: BuiltinByteString -> BuiltinByteString
sha2_256 = BI.sha2_256

This BI.sha2_256 function in the PlutusTx.Builtins.Internal is defined at (2). Here the function is wrapped in the BuiltinByteString type. A function is imported from the the Hash module.

{-# NOINLINE sha2_256 #-}
sha2_256 :: BuiltinByteString -> BuiltinByteString
sha2_256 (BuiltinByteString b) = BuiltinByteString $ Hash.sha2 b

This Hash.sha2 function in the Data.ByteString.Hash is defined at (3). Here it gets a bit more complicated. A cryptographic hash function takes an arbitrary block of data and calculates a fixed-size bit string (the digest). Since there may be other hash function (like the SHA3_256 version in PlutusTx) the function is abstracted to a general hash function where the type inferred by the type application @SHA256). This data type and its instance of a hash algorithm is imported from Cardano.Crypto.Hash.SHA256.

-- | Hash a [[BSL.ByteString]] using the SHA-256 hash function.
sha2 :: BS.ByteString -> BS.ByteString
sha2 = digest (Proxy @SHA256)

In this cardano-base package the module Cardano.Crypto.Hash.SHA256 defines the data type SHA256 and its instance of a hash algorithm at (4). The function sha256_libsodium is also defined there. This function uses another function called c_crypto_hash_sha256, this is where it gets interesting imported from the module Libsodium.C.

data SHA256

instance HashAlgorithm SHA256 where
  type SizeHash SHA256 = 32
  hashAlgorithmName _ = "sha256"
  digest _ = sha256_libsodium

The function c_crypto_hash_sha256 in Cardano.Crypto.Libsodium.C (like many other cryothographic derivatives used in cardano) is defined in (5). Here this function is actually import from the package Libsodium which is a library for encryption, decryption, signatures, password hashing and more written in C.

Now my question is, how is this lower level C function get used in the lower level Fμω lambda calculus onchain? Does each node just invoke/inject the C function once the lambda calculus references it?