2021-12-29

Pulseaudio: Multi-User Setup

Hello and welcome to my blog. If you are finding this page, then you might be in a similar situation I found myself when I wanted to share audio with different apps if they were being used by different user accounts on your local *nix machine when using Pulse audio.

Credits to Eli Billauer and Dhole for the configuration directives I needed to make this possible.

The Problem

I have multiple user accounts on my system that run various apps, like my web browser, chat apps, email and more. I don't like everything running as myself and try to create a user account with just enough privileges to do what it needs to do.

Pulseaudio (herein "Pulse") runs as myself when my desktop environment starts. Apps that run normally need to connect to Pulse in some fashion in order to listen to the microphone or play audio on the speakers. When the apps all run as the logged in user, this works great. When the apps run as someone else, this doesn't work or is inconsistent in behaviour.

The Scenario

I have a user account chrome that is dedicated to the browser /usr/bin/google-chrome-stable. The browser will run as this account instead of myself and has just enough permissions to render on the screen and have basic access to some files on the filesystem (albeit, as the unprivileged account).

How do I make it possible to render sound and grant access to the mic when necessary to chrome?

The Solution

I use local UNIX sockets to allow applications to talk to Pulse and the system behaves. I also discovered you DO NOT need to modify the system configuration files in /etc.

There's a few configuration files and directives that are used and will be laid out here.

Server Configuration

As the user who runs Pulse (e.g. creates the server):

  • Create ~/.pulse if it doesn't exist already.
  • Create and populate ~/.pulse/default.pa with the content as described below in the block of configuration.
    • Please note: Pulse will look for local configurations before global configs and will stop looking for additional files once it finds a match. The configuration is not a layered configuration in that /etc is applied first, then local configuration overrides those values. If a local file is present, it should include all dependencies and global configuration files or else you could end up with a misconfigured setup.
  • Restart Pulse. Can use pulseaudio -k && pulseaudio -D. Please consult your distribution's documentation if the mechanism to start Pulse are different for you.
  • Personally, I had to chmod o-rwx /tmp/pulse-server (aka chmod 770 /tmp/pulse-server) to remove access to the socket outside of me and those part of the audio group I wanted apps to share if they were going to be using audio streams.

Pulse may run as yourself or a dedicated user just for dealing with sound.

~/.pulse/default.pa:


.include /etc/pulse/default.pa

#load-module module-native-protocol-tcp auth-ip-acl=127.0.0.1

### Load several protocols
load-module module-dbus-protocol
.ifexists module-esound-protocol-unix.so
load-module module-esound-protocol-unix
.endif
load-module module-native-protocol-unix auth-group=audio socket=/tmp/pulse-server

Client Configuration

As someone who will connect to Pulse and attempt to interact with the speakers and/or microphone, you'll need to include this configuration in every users' home directory under ~/.pulse/client.conf:

# Unix socket method
default-server = unix:/tmp/pulse-server
enable-memfd = yes

With this configuration, as each app started up, I noticed they were able to interact with audio without issues. I also restarted my Bluetooth daemon and was able to pass audio through my BT-headset!

2021-12-09

Airdrops!

Airdrops!

Link to Previous Post.

I admit, I left that last post to be quite vague (but it got your attention, didn't it?). So let's address that in today's video!

Just like Linus from Linus Tech Tips says: Do you like FREE MONEY!?!?

Airdrops are just that! For participating in a network and being an early adopter of the technology, you can have coins dropped right into your wallet. Some of these airdrops are setup in such a way that requires you to claim those tokens.

Previous Airdrops

Previous notable airdrops include the Uniswap airdrop in which users of the Uniswap application before the airdrop received up to 400 UNI tokens just for making a decentralized trade on this DeFi application! In today's value, that's worth up to $7100 as of this recording!

ENS is another recent airdrop that happened to stumble upon the market. ENS is the Ethereum Name Service. Kind of like DNS, but for your crypto address. When I heard about this service that was coming out, I had to register markizano.eth! I didn't know it at the time, but they later come out with an airdrop. If you registered an ENS domain name before the snapshot was taken in October, you can claim your bounty at https://claim.ens.domains/

Currently, ENS is trading at $50 at the time of recording, so an airdrop of 50 ENS would be worth around $2500! That's a pretty good chunk of change for just registering a domain name on the Ethereum network!

Future Airdrops

If you want to hunt down future airdrops, you can navigate to https://coinmarketcap.com/airdrop/ There, they have a listing of the upcoming airdrops. Currently 13 are in progress as of the recording of this video. 2 more airdrops are coming soon and this appears to be new because they weren't there yesterday.

You can also follow VoskCoin on YouTube. Another source of potential airdrops would be the Coin Bureau. Tell them Markizano Draconus sent you, with love <3 =D

There are 2 airdrops I'm particularly watching out for and those include:

  • Zapper.fi with a potential ZAP token.
  • Metamask with a potential META token. Better snatch it before Facebook does!

Checkout zapper.fi - it's a blockchain cralwer that gives you a general view of your wallet and compatible with Metamask.

Install Metamask, the browser extension and experiment with some DeFi things and have some fun with crypto! Not financial advice, just some fun to have with crypto!


2021-12-07

IPFS: Inter-Planetary FileSystem

IPFS: Inter-Planetary FileSystem

IPFS is the Inter-Planetary FileSystem. It's used to direct people to content instead of addresses. When you look for a file on the network, you typically type some URL into your browser that navigates you to some website. The address contains the "who" your browser should talk to in order to receive data back. Data may only ever exist on that website and cannot be found elsewhere (unless you download that content and host it yourself).

In IPFS, you can have multiple gateways that serve content from a decentralized backend filesystem. Data is stored on IPFS and a hash of that data is rendered back to you. In this way, anyone hosting an IPFS gateway can serve any file that was previously stored on the IPFS network without having to go through a central authority. You could even host your own IPFS gateway to have faster access to the files that matter to you most.

People can upload content into an IPFS and that data can be stored indefinitely. People host full-blown websites! Blockchains based on currency (like RVN, ETH and SOL) use these as utility to store blob data like videos, images and music. This enables these blockchains to focus on what they do best while letting other blockchains focus on storing the data that they want to track.

Cryptocurrency Examples

There are a few cryptocurrency projects that leverage IPFS. The most notable is FileCoin (ticker: FIL). Other projects include Siacoin (ticker: SC), Storj (ticker: STORJ) and Swarm (ticker: BZZ). These projects enable folks to utilize IPFS and earn rewards for keeping your data safe.

The general idea is this:

  • There are people who have extra disk space not doing anything.
  • They can allocate some of this disk space to the network.
  • They would receive rewards for keeping your data secure in this decentralized cloud filesystem. For some projects like FileCoin, rewards for them are slashed or even removed if their node ever goes down. In this way, there's a high level of incentive to maintain stability of the storage space available on the network. Anyone ever had a drive fail on them in the middle of a torrent download?

You can find out more about this technology at docs.ipfs.io. They have everything from running your own node, uploading files to the network and much more!


2021-11-11

What's a Crypto: BTC - BitCoin!

BTC: Bitcoin!

Structure

Bitcoin is a peer-to-peer (P2P) payment network that enables folks to send money to each other without some intermediate financial institution like a Bank or Broker. Similar to the Tor network, but with money.

This was setup to avoid needing a trusted third party to validate transactions. That trust can be broken and manipulated depending on the entity in charge of the financial transactions.

Transactions are secured against double-spending via hashing timestamps along with the transaction information itself. Bitcoin is transferred from one party to another via computational power that attempts to collect all the transactions since the last block and create a new chain of transactions. The longest chain with the most history is the victorious chain that will have more blocks added to it.

* This is why when you transact on any cryptocurrency network, most often times, you'll see say "your funds are locked until X number of confirmations"; they want to be certain an attacker doesn't have the opportunity to "unspend" those coins.

Proof of Work

Proof of work is when CPU power is expensed to calculate the transactions into a chain. We've covered this concept in a previous video, but to expand on the previous explanation, let's imagine a tree instead of a box for a block. As each transaction comes into the network, it's also marked with a timestamp. These computers are all trying to create a chain of transactions that make sense and includes as many transactions as it can into the block of transactions.

Rewards

To incentivize people to secure the network, rewards are granted for the computing power invested in securing the network.

The genesis block is the first block on the chain and includes the original 50 BTC that was first ever minted. Every transaction after that is either the transfer of those original 50 BTC, or the minting of 50 new BTC. Every 210,000 blocks, the rewards are cut in half.

In addition to the block reward, transaction fees are included in the block as well. This will continue to incentivize people to secure the network even after all blocks have been mined. Each new block added to the chain includes the block reward as the first transaction, all other transactions and their fees are added up and sent to the address that found the next block all miners can agree to start working on next. The block reward itself is called the Coinbase block. Seems there's a bit of a cooincidence in the name of the company.

Transactions

Transactions are made via the PKI infrastructure we talked about in a previous video. Using this private/public key setup, the recipient is able to sign the request with the public key and the sender is able to verify it with their private key. This is why it's absolutely critical you have a secure lock on your private key (e.g. your seed phrase) because with that, an attacker can completely replicate your wallet, its contents and sign transactions on your behalf.

Privacy

Your privacy is secured via the "anonymity" of your public key being open and on the network, but nobody knowing its you until you associate yourself with that public key as your identity.

Exploits

Now, let's talk about the security of BitCoin.

An attacker is only ever able to try to reverse transactions where they spent their Bitcoin; Bitcoin can never just appear out of thin air from an exploited chain of blocks because it would be rejected by the honest players in the network.

An attacker would need at least 51% of the hashing power of the network to perform an attack. However, this could only ever be an attack that could "unspend" the coins, or allocate the block reward to an address they control. This is not beneficial to the attacker because then the coin would lose its value from the lack of trust in the network.

An attacker can also "guess" at the seed phrase used to generate a wallet. However, this isn't really practical because they would need that entire nemonic phrase in order to replicate your wallet.

All in all, Bitcoin as a network is actually really secure itself. The exploit vector is you.

Conclusion

So, Bitcoin itself is very secure and has great incentive to remain as such. Bitcoin does one thing, and it does it well: Store of value and transfer of that value.

So stay smart. Stay safe. Take care of yourself and others. Think before you click!


Sources:


Hashing vs Encryption

Hashing vs Encryption

Today, we're going to take a look at the difference between Hashing and Encryption. It should be a nice and quick video since the explanations can be made relatively simple.

Hashing

Hashing is one way. You can take any amount of data and reduce it down to a series of hexadecimal characters that are a fixed length. Some examples of hashing algorithms include MD5, SHA1, SHA256.

In some cases and for some algorithms like MD5, the results can clash. Clashing happens when you take more than one input and get the same output. For an oversimplified example, I input "AAAA" into the MD5 algorithm and get a hash. I input "CCCCCC" into the algorithm and get the same hash. You can say there is a clash in the MD5 algorithm between those two values.

For security, you'll want to select an algorithm that has a low number of clashes to avoid the chances at "reverse hashing" the data you put into the algorithm.

Reverse Hashing

Reverse hashing is really a term that is coined off this concept here:

  • I will execute a bruteforce password cracking attack and create a hash of "a", then "b", then "c".
  • I will repeat for "aa", "bb", and "cc".
  • I will repat until "zzzzzzzz".

This is called creating a Rainbow Table, in which you get a text file that represents the hash and the input that created the hash. So, really it's not "reverse hashing" as much as it's a "reverse table lookup for the hash" to determine the source of data that went into the algorithm.

Hashing Examples

Real world example cases of hashing include passwords. As a developer, you should never store passwords in plaintext. You should always hash them (with a salt) and store the result. If the user enters the same password and it's correct, the hashes should match. If not, reject the login.

Encryption

Encryption is the act of taking information and altering the value of that data until its unrecognizable. An oversimplified example could be to suppose you take the alphabet and reverse the characters. Z is A, B is Y and so on. The result would appear to be unreadable to anyone who doesn't know the algorithm that went into encrypting the data.

Encryption is reversable. You need to know the algorithm and the rules that go into that encryption. Some encryption is really simple and just requires a password. Other encryptions require a password and a key. More advanced algorithms require a password, key and IV or Initialization Vector.

Encryption Keys

An encryption key is not limited to just encryption, but also can be used for authentication and authorization. In a previous video, we covered the concept of PKI or Public Key Infrastructure. This can also be used to sign the encryption to also verify the property of key ownership. If you need to validate identity, then keys will be used to sign the encryption as well to ensure the party is not only the only one who can view the data, but also the person to whom you think you're speaking.

Initialization Vector

An Initialization Vector (IV) is basically a seed random number that kicks off the encryption algorithm. You can think of the IV as the spark plug that starts the encryption engine.

Summary

So that's hashing vs Encryption in a nutshell. Hashing is one-way and cannot be reversed. However, there's nothing stopping you from creating a database of hashes to values. Encryption is reversable, but you need to know the rules of engagement before embarking upon this journey.


2021-11-02

New Series: What's a Crypto?

This is an editorial edutainment post.

Intro

So, we are going to start a new series called: What's a Crypto? In these episodes, we're going to cover several cryptocurrencies. We'll be examining the project, their purpose, use cases, and how to apply some of the concepts we've covered on my channel.

Before we get into that, there are a few technical terms we will need to cover first that aren't directly related to cryptocurrency, but apply to technology on a more general level.

These include:

  • PKI: Public Key Infrastructure
  • Hashing vs Encryption

In our first two episodes, we're going to cover: Bitcoin and Ethereum!

We'll take a look at the Whitepaper, what it says and we'll look at some use cases. If there's anything else relevant, we'll include that as well. If you have any coins you want me to cover, drop a comment below!

If you're seeing this video, it means at least Bitcoin is live, so head on over to my profile and find the video with the poster label: "BTC" I'll label the videos according to the ticker symbol found in most exchanges.

If you found this helpful, then you should double-tap that screen for a like! If you like learning about cryptocurrencies and all their fun applications, you should subscribe :) If you have any coin requests, drop a comment below and I'll cover it in one of my upcoming videos.

I have several coins on my list I plan on publishing so stay tuned!


2021-11-01

PKI: Public Key Infrastructure

PKI: Public Key Infrastructure

This is an editorial edutainment post.

PKI is a set of rules and policies that enables the transfer of information in a secure manner. It can be as simple and informal as two parties exchanging information securely among themselves, or it can be a larger integration where a third party validates the sender and recipient via signing the keys used in the exchange.

Structure

PKI involves at least two pairs of keys. A public and a private key. I generate a key pair. You generate a key pair.

The public key is open to the world and can be shared with anyone. Anyone can use the public key to encrypt information, or securely lock it so nobody else can read said data. You can equate the public key to this Master lock in this example.

The private key is yours and yours alone!

Don't share your privates in public, got it private?

The private key is used to decrypt anything encrypted with the public key. The private key is the only way to access data once it's been encrypted with the public key.

This is why folks often say "backup your keys/wallets" in cryptocurrencies. You never want to be in a single point of failure and lose the only key that can access your data. So, when you encrypt your data, be sure to make a copy of the password or key that encrypted that data.

Security

To further enhance the security of this setup, you can optionally encrypt your private key with a password/passphrase. This is a passphrase that is used to access the private key before decryption takes place.

It's like taking your key and putting it into a mini-safe that requires a PIN to access instead of just laying on your counter.

Keep in mind: The key is only as safe as your password.

This is why the cryptocommunity advocates using offline storage like a hardware wallet to store your crypto to avoid the chance at malicious software from ever accessing your private keys.

Simple Exmple

For a simple example, let's assume we want to exchange information in a secure manner. In this case: I would send you a copy of my public key. You would send me a copy of your public key.

If I wanted to send you data, I would take your public key, encrypt the data with that public key and send the result to you. Rest assured nobody will be able to view or intercept the data unless they have the private key you own, hold and control.

If you want to view the data and interact with it, simply use your private key to decrypt and see the plain version of the data.

Likewise: If you want to send data to me, then you would use my public padlock I gave to you to encrypt the data and send it back to me with the confidence that I will be the only one who will have access to said data via using my private key to decrypt the data.

This relates to cryptocurrency because your wallet is basically a public-private key pair. When you see that 12 word mnemonic phrase and your wallet tells you to backup that phrase, basically, that phrase is the private key that is used to generate the wallet.


@markizano.draconus

Let's talk about ##PKI or ##PublicKeyInfrastructure ##CryptoTalk ##Crypto ##Blockchain ##bitcoin ##ethereum

♬ original sound - Markizano Draconus

2021-10-25

SmartContracts!

SmartContracts

This is an edutainment post.
@markizano.draconus

Let's talk about ##SmartContracts ! ##bitcoin ##CryptoTalk ##Blockchain ##ethereum ##Cryptocurrency

♬ original sound - Markizano Draconus

So let's talk about SmartContracts!

The What

Smart Contracts are programs stored on Blockchain technology that are executed when certain conditions are met.

You can think of SmartContracts programmable money! Imagine if/then statements embedded in your monetary transactions!

Application

SmartContracts can be written in a few languages like Solidity and Rust. You can write these programs to do things like detect changes in other Blockchains using ChainLink, automatically distribute money when certain conditions are met and so much more!

Example

A common example of a SmartContract could be an insurance policy. Let's say we have an oracle, like ChainLink recording temperature and weather data and writing that on its Blockchain. A SmartContract could be written to do a few things:

  • When you pay into this contract, start up a policy.
  • This policy will begin to monitor the temperature and the weather.
  • If it doesn't rain for a consecutive 90 days || or || if the average 90 day temperature is above 95F, then...
  • Pay out the farmer the investment on the policy to ensure he's compensated for the loss.
  • IF not: pay the shareholders back their investment.

Summary

SmartContracts have a lot of potential to do a lot of things including creating entire organizations. but those are DAO's and that's for another video worth a subscription ;)

2021-10-24

NFT: Non-Fungible Token

NFT's: Non Fungible Tokens

This is an editorial edutainment post.
@markizano.draconus

So let's talk about ##NFT 's! ##NonFungibleTokens ##Crypto ##CryptoTalk ##Bitcoin ##ethereum

♬ original sound - Markizano Draconus

So let's talk about NFT's, or, Non Fungible Tokens!

NFT's, or Non-Fungible Tokens are certified unique items! There will only ever be 1!

NFT's are mostly applied to Art. So imagine having the Mona Lisa. You got it from the original artist and you hold one of the few originals created in the world. I can take a picture of it all day long and print that picture, but it's not the original artwork! An NFT is a representation of the original work and can be verified on the blockchain.

Ownership of an NFT can be single or many. However, it's not like cutting off pieces of the Mona Lisa. Instead, it's more like a company: Where you have stakeholders in the company and multiple owners of the same entity.

That is a common way to explain an NFT, but it's by no means the only way to apply it.

Anytime you need to sign, certify or agree to something? That can be an NFT!

Now, this might be years in front of us with policy and what have you, but, putting all that aside for a moment, your vote can be an NFT. There will only ever be one and its identity is linked to you.

Now, imagine being able to design your home: The floor plan and where everything is laid out. Now, imagine being able to have that 3D printed... Once printed, you can take the design and layout and create an NFT out of it. Want to sell your home? Transfer ownership of the NFT to the next party. Taking on a roommate? Simply dilute ownership so you both have a name on the deed. Ready to move out? Simply sell the diluted ownership to the party taking over the house.

I know NFT's have mostly been applied to Art. However, that's not the limit and there's so much more to be had with NFT's, it's unfathomable!

2021-10-23

BITO: The New BitCoin ETF!

BITO: Proshares Bitcoin Strategy ETF

This is an editorial edutainment post.
@markizano.draconus

Let's talk about the new ##Bitcoin ##ETF ! ##Crypto ##CryptoTalk ##investing ##BITO

♬ original sound - Markizano Draconus

This is the ticker symbol for the new ETF on the market today as of 2021-10-18. This ETF will not be what you'd expect since it's not a traditional ETF. In most cases, when you buy into an ETF, it will go and buy an equivalent amount of the underlying asset. If there are underlying stocks, real estate, or precious metals like gold and silver, the ETF would go and purchase the actual underlying asset.

Indirectly, this can impact the price of Bitcoin, but not in the way you would think and by no means would it be predictable nor consistent for at least five years (personally, I believe).
This does two major things that I see:

  • It gives institutions that must abide by financial governance ability to invest in Bitcoin without owning it.
  • It re-creates the same issue with gold into fiat in that they are dilluting the value of a promise in place of the actual asset itself.

I also believe this is a great first step for the long-term investor who might still be skeptical of the Power of BitCoin™ and its possiblity and potential. The Future of Finance is now and we are witnessing its construction.

What do you think?
Drop a comment below.

2021-06-17

Build xmrig on Linux

Hi all,

So, I am getting into the crypto-mining space a bit and I wanted to share a few things I've learned. This whole experience has been teaching me a lot as of late!
In this post, we'll be talking about xmrig what it is and how to compile it on Linux. I'm going to skip the wallet and other details as I wanted this post to be as context-specific and straight to the point as possible. Let's dive right in.


What is xmrig???

My take on this is xmrig is a swiss army knife of a mininig tool that can be used for many algorithms and various coins. I mostly found and used this to mine Monero (XMR), so we'll take that as an example. xmrig supports both CPU and GPU minining, but not all algorithms are CPU- or GPU- friendly. Some are specific to either, so be mindful of what you are doing when you are setting this up.
Let's dive into the build and running instructions and examples.

Building xmrig

I happen to be using debian-based systems to compile stuff. So you'll see some aptitude references in the installation scripts.
I also happen to have this handy script I used to install xmrig on various machines I have without having to think about much. Here's the script for reference: [1].

Script Notes

RUNNING AS ROOT: One thing to note about scripts that I write: I dislike things running as root. There were a lot of posts out there which said the problem was resolved once they ran the command as root. I don't know about you, but I really don't feel comfortable running some untrusted code as root in my system. I like to understand what its doing and give it just enough capabilities to do its job. So, I found out what those capability requirements were and baked them into this script.
As long as you use the resulting mine.sh script (or concepts from it), you should have a little more confidence that this does not require escalated privileges.

CUSTOMIZATION: Be sure to customize this with your preferences. For example, the mining pool of your choice, along with your wallet address. I noted these below in the script.

SUDO: No need to run the build script as root since it will sudo its way to privilege when necessary. Just make sure the user who runs the script has ability to run sudo commands.
However, you do need to run the resulting mine.sh script as root since it will set some options and drop privileges before executing your miner.

SETCAP: This is one of those low-level operations I discovered that normally requires root privileges. However, if there's one thing I have learned about Linux: If you have the right capabilities, you don't require root for anything (except to grant said permission, even then, you can dedicate a user to just that action). If you know what you are doing, you can avoid the root user for just about anything. One of the greatest strengths of Linux I love so much. I think this is why people just flatly said "just run it as root" and left it at that. With this capability set on the binary, it tells the system that it's okay for this particular process to perform this action without escalated privileges.

Building/Execution

It should be as simple as executing the script. However, if months or years later you are coming across this blog post and the version has since changed, I left an easy add to that via an environment variable. So you can use:

    
xmrig_version=6.12.0 ./xmrig-build-all.sh
    
  

In order to compile this.
After the script executes and the code is built, I install the results to /usr/local/share/xmrig/xmrig-$xmrig_version and name the file accordingly. If you want CUDA support, run the script with that variable set to something non-empty as such:

    
WITH_CUDA=1 xmrig_version=6.12.0 ./xmrig-build-all.sh
    
  

Donations

Donations are greatly appreciated if you found this to be helpful!

  • BTC: 3KpGAGUFEbdpXZvLtPRRdzpVATwEHVCkRJ
  • ETH: 0xBfF52D9A244A1C333573f903737ec5eDb5a99150
  • DOGE: D89MZHmmFewdyksCs8EnXwj8XFn7AXrNsj
  • XMR: 49NE1L9WVJLcg7susCGSTAcbT5Fi8Ukq1JthDSjWkLdM6VrnvtZEdm7Vh36gFmdfR2hqKQ1pUKXT71BY9rKsUW3GJUL3Cbr
  • RVN: RMvGF8qpY3XjrGMuzfAMkwveehmqgZrhcF
I plan on posting several new pages about what is crypto and getting into these miners as I complete my research.
Thanks for taking the time to read through this!

[1]: xmrig-build.sh

    
#!/bin/bash -e

# This is the script we will be using to mine later.
# Stored as a string for us to write to a script file later in this installation script.
XMR_MINE_SCRIPT=$'#!/bin/bash

# While root, relax the memory limits and set permissions on the MSR stuff
#  for the CPU since it seems to revert at each reboot.
test "$UID" -eq 0 && {
  ulimit -l 10240
  modprobe msr
  chgrp msr /dev/cpu/*/msr
  chmod g+rw /dev/cpu/*/msr
}

RUNAS_USER=xmr
RUNAS_GROUP=apps
test "$UID" -eq `id -u $RUNAS_USER` || {
  echo "Dropping privileges..."
  exec sudo -H -u$RUNAS_USER -g$RUNAS_GROUP \
    MINER_DEBUG=${MINER_DEBUG} \
    MINER_POOL=${MINER_POOL} \
    MINER_WALLET=${MINER_WALLET} \
    MINER_NAME=${MINER_NAME} \
    MINER_HOME=${MINER_HOME} "$0" $@
}

test -z "$MINER_DEBUG" || {
  set -x
}

MINER_POOL=${MINER_POOL:-"my-favorite-mining-pool.org:3333"}
MINER_WALLET=${MINER_WALLET:-"45n1_MY_WALLET_ADDRESS_0x23943"}
MINER_NAME=${MINER_NAME:-`hostname -s`}

cd

exec xmrig --threads=`nproc` \
  -o "${MINER_POOL}" \
  -u "${MINER_WALLET}" \
  -p "${MINER_NAME}" \
  -k --tls --coin monero $@
'

# Setup some variables and build the xmrig software.
xmrig_version=${xmrig_version:-6.12.0}
xmrig=~/git/cryptocurrency/xmrig

cuda_version=${cuda_version:-$xmrig_version}
cuda=~/git/cryptocurrency/xmrig-cuda

# If you use RHEL/Arch/Gentoo/Other, replace this with your pkg-mgr and names of the respective packages.
sudo apt-get install -y git build-essential cmake libuv1-dev libssl-dev libhwloc-dev msr-tools

# https://stackoverflow.com/questions/18661976/reading-dev-cpu-msr-from-userspace-operation-not-permitted
# Found out why I get the MSR error. This is the fix.
modprobe msr || true
grep msr /etc/group || sudo groupadd --system msr
sudo chmod g+rw /dev/cpu/*/msr
sudo chgrp msr /dev/cpu/*/msr

test -d $xmrig || git clone --depth 1 --branch v$xmrig_version git@github.com:xmrig/xmrig $xmrig
test -d $xmrig/build || mkdir $xmrig/build

test -z "$WITH_CUDA" || {
  test -d $cuda  || git clone --depth 1 --branch v$cuda_version git@github.com:xmrig/xmrig-cuda $cuda
  test -d $cuda/build  || mkdir $cuda/build
}

test -d /usr/local/share/xmrig || sudo install -d -oroot -gstaff -m2755 /usr/local/share/xmrig

(
  cd $xmrig/build
  cmake ..
  make -j`nproc`
  sudo install -v -oroot -gstaff ./xmrig /usr/local/share/xmrig/xmrig-$xmrig_version
  # This sets a capability on the binary itself in order to have raw IO operations against the CPU for MSR to work.
  sudo setcap cap_sys_rawio=ep /usr/local/share/xmrig/xmrig-$xmrig_version
)

test -z "$WITH_CUDA" || {(
  cd $cuda/build
  # If you have issues with cuda, add the following to specify it directly:
  #  -DCUDA_LIB=/usr/local/cuda/targets/x86_64-linux/lib/stubs/libcuda.so -DCUDA_TOOLKIT_ROOT_DIR=/usr/local/cuda
  if [ `gcc -dumpversion` -ge 10 ]; then
    # xmrig-cuda does not appear to support gcc-10 just yet. If this changes,
    # remove this if(){} block and the subsequent variable from `cmake'.
    CMAKE_OPTS='-DCMAKE_C_COMPILER=gcc-9 -DCMAKE_CXX_COMPILER=g++-9'
  fi
  # Change CUDA_ARCH to what works for your installation: https://developer.nvidia.com/cuda-gpus
  cmake .. -DCUDA_ARCH=61 $CMAKE_OPTS
  make -j`nproc`
  sudo install -v -oroot -gstaff ./libxmrig-cuda.so /usr/local/share/xmrig/
  slaves="--slave /usr/lib/libxmrig-cuda.so libxmrig-cuda.so /usr/local/share/xmrig/libxmrig-cuda.so"
)}

# Make the software live and available to the rest of the system thru update-alternatives.
sudo update-alternatives --install /usr/local/bin/xmrig xmrig /usr/local/share/xmrig/xmrig-$xmrig_version 100 $slaves

# Enable hugepage support.
sudo sysctl -w vm.nr_hugepages=1280

# setup the non-privileged account that will enable us to mine!
getent group crypto >/dev/null || groupadd --system crypto
group_gid=`getent group crypto | cut -d: -f3`
id xmr || sudo useradd --gid=$group_gid --shell /usr/sbin/nologin --system --home /var/lib/crypto/xmr -m -G msr xmr
test -d ~xmr/bin || sudo install -d -oxmr -gapps ~xmr/bin
test -f ~xmr/bin/mine.sh || echo "$XMR_MINE_SCRIPT" | sudo install -oxmr -gapps /dev/stdin ~xmr/bin/mine.sh

echo "You can now run sudo /var/lib/crypto/xmr/bin/mine.sh"
echo "Complete!"